>  기사  >  백엔드 개발  >  PHP의 Foreach 루프 내에서 배열 키를 검색하는 방법

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

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-10-17 17:20:32296검색

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.