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 "<tr><td>" . key($item) . "</td><td>" . $sampleArray['value1'] . "</td><td>" . $sampleArray['value2'] . "</td></tr>"; }</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 "<tr><td>" . $key . "</td><td>" . $item['value1'] . "</td><td>" . $item['value2'] . "</td></tr>"; }</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.
Das obige ist der detaillierte Inhalt vonSo rufen Sie Array-Schlüssel in der PHP-Foreach-Schleife korrekt ab. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!