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

PHP Foreach 루프에서 배열 키를 올바르게 검색하는 방법

Linda Hamilton
Linda Hamilton원래의
2024-10-17 17:19:02605검색

How to Correctly Retrieve Array Keys in PHP Foreach Loop

Retrieving Array Keys in a Foreach Loop: Addressing an Error in Key Retrieval

In PHP, iterating over an array's values using a foreach loop can sometimes lead to unexpected behavior when accessing the keys. This is especially true if the array contains nested data structures.

Understanding the Error

Consider the following code:

<code class="php">foreach ($sampleArray as $item) {
    echo "&lt;tr&gt;&lt;td&gt;" . key($item) . "&lt;/td&gt;&lt;td&gt;" . $sampleArray['value1'] . "&lt;/td&gt;&lt;td&gt;" . $sampleArray['value2'] . "&lt;/td&gt;&lt;/tr&gt;";
}</code>

As illustrated in the provided question, this code will only output the key of the nested array (e.g., "value1"), not the desired key of the outer array itself (e.g., "4722").

Correcting the Issue

To retrieve the outer array key correctly, we need to modify the code slightly:

<code class="php">foreach ($sampleArray as $key => $item) {
    echo "&lt;tr&gt;&lt;td&gt;" . $key . "&lt;/td&gt;&lt;td&gt;" . $item['value1'] . "&lt;/td&gt;&lt;td&gt;" . $item['value2'] . "&lt;/td&gt;&lt;/tr&gt;";
}</code>

By adding a $key variable to the foreach loop, we can access the actual key of the outer array. This will then correctly print the desired key in the table.

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

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