首頁 > 後端開發 > php教程 > 如何在 PHP 中使用 foreach 存取特定索引處的巢狀陣列?

如何在 PHP 中使用 foreach 存取特定索引處的巢狀陣列?

Mary-Kate Olsen
發布: 2024-10-17 22:07:02
原創
689 人瀏覽過

How to Access a Nested Array at a Specific Index Using foreach in PHP?

PHP foreach with Nested Array

Question: How to access a specific nested array using a foreach loop in PHP?

Consider the following nested array:

<code class="php">array(
    [0] => array(
        [0] => one
        [1] => array(
            [0] => 1
            [1] => 2
            [2] => 3
            )
        )

    [1] => array(
        [0] => two
        [1] => array(
            [0] => 4
            [1] => 5
            [2] => 6
            )
        )

    [2] => array(
        [0] => three
        [1] => array(
            [0] => 7
            [1] => 8
            [2] => 9
            )
        )
    )
);</code>
登入後複製

The goal is to iterate through the values of the nested array at key 1, without using a variable comparison.

Answer: There are two approaches to achieve this:

1. Nested Loops (Fixed Depth):

This method is suitable if the depth of the nested arrays is known in advance.

<code class="php">foreach ($tmpArray as $innerArray) {
    if (is_array($innerArray)) {
        foreach ($innerArray as $value) {
            echo $value;
        }
    } else {
        echo $innerArray;
    }
}</code>
登入後複製

2. Recursive Function (Unknown Depth):

This approach is used when the depth of the nested arrays is unknown. It involves a recursive function that traverses the array:

<code class="php">function displayArrayRecursively($arr, $indent='') {
    if ($arr) {
        foreach ($arr as $value) {
            if (is_array($value)) {
                displayArrayRecursively($value, $indent . '--');
            } else {
                echo "$indent $value \n";
            }
        }
    }
}

$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(7, 8, 9))
);

displayArrayRecursively($tmpArray);</code>
登入後複製

Specific Case:

To access only the nested array with values for the third level (key 2), use the following code:

<code class="php">foreach ($tmpArray as $inner) {
    if (is_array($inner)) {
        foreach ($inner[1] as $value) {
            echo "$value \n";
        }
    }
}</code>
登入後複製

以上是如何在 PHP 中使用 foreach 存取特定索引處的巢狀陣列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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