首頁 > 後端開發 > php教程 > 如何在 PHP Foreach 迴圈中檢索巢狀數組的數組鍵?

如何在 PHP Foreach 迴圈中檢索巢狀數組的數組鍵?

Barbara Streisand
發布: 2024-10-17 17:22:02
原創
738 人瀏覽過

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.

以上是如何在 PHP Foreach 迴圈中檢索巢狀數組的數組鍵?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板