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

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

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-17 22:07:02576瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn