Heim  >  Artikel  >  Backend-Entwicklung  >  Wie rufe ich Array-Schlüssel in einer PHP-Foreach-Schleife für verschachtelte Arrays ab?

Wie rufe ich Array-Schlüssel in einer PHP-Foreach-Schleife für verschachtelte Arrays ab?

Barbara Streisand
Barbara StreisandOriginal
2024-10-17 17:22:02622Durchsuche

How to Retrieve Array Keys in a PHP Foreach Loop for Nested Arrays?

PHP: Retrieving Array Keys in Foreach Loop

In PHP, iterating over an associative array using the foreach loop provides access to both the values and keys. However, the key() function only returns the current value's key, which can be insufficient when working with nested arrays.

For instance, consider an array like this:

<code class="php"><?php
$samplearr = array(
    4722 => array('value1' => 52, 'value2' => 46),
    4922 => array('value1' => 22, 'value2' => 47),
    7522 => array('value1' => 47, 'value2' => 85)
);
?></code>

If you attempt to use key($item) in a foreach loop to retrieve the parent key, you may encounter unexpected results:

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

This code only returns the value keys: value1 and value2.

To access the parent keys, you can use the following approach in the foreach loop:

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

By using $key, the loop iterates over the parent keys, allowing you to access and print both the parent and child values as desired.

Das obige ist der detaillierte Inhalt vonWie rufe ich Array-Schlüssel in einer PHP-Foreach-Schleife für verschachtelte Arrays ab?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn