PHP의 Foreach 루프 내에서 배열 키를 검색하는 방법

Mary-Kate Olsen
풀어 주다: 2024-10-17 17:20:32
원래의
290명이 탐색했습니다.

How to Retrieve Array Keys within a Foreach Loop in PHP

Retrieve Array Keys During Foreach Loop: PHP

When working with arrays in PHP, it's often necessary to retrieve both the keys and values within a foreach loop. The key() function provides a convenient way to access the current key during the iteration. However, in certain scenarios, it may not yield the desired result.

Consider the following code that aims to generate an HTML table from the sample array:

<code class="php">foreach($samplearr as $item){
  print "<tr\><td>" . key($item) . "</td>\><td>" . $samplearr['value1'] . "</td>\><td>" . $samplearr['value2'] . "</td>\></tr\>";
}</code>
로그인 후 복사

This code incorrectly returns the key as "value1" instead of the actual key of the outer array (e.g., 4722).

To resolve this issue, it's necessary to use the array key as the iteration variable:

<code class="php">foreach($samplearr as $key => $item){
  print "<tr\><td>" . $key . "</td>\><td>" . $item['value1'] . "</td>\><td>" . $item['value2'] . "</td>\></tr\>";
}</code>
로그인 후 복사

By declaring the loop variable as "$key," you can directly access the key of the outer array within the loop. This code will now correctly generate the expected HTML table:

<code class="html"><tr\><td>4722</td>\><td>52</td>\><td>46</td>\></tr\>
<tr\><td>4922</td>\><td>22</td>\><td>47</td>\></tr\>
<tr\><td>7522</td>\><td>47</td>\><td>85</td>\></tr\></code>
로그인 후 복사

위 내용은 PHP의 Foreach 루프 내에서 배열 키를 검색하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!