PHP 每个循环在数组中更深一层

2022-01-07 00:00:00 arrays loops nested php

我正在尝试遍历一个数组,每次都向另一个数组添加一个新级别.让我举例说明——变量 $arr 的值每次都不同

I'm trying to loop through one array, adding a new level to another array each time. Let me illustrate - variable $arr's values are different each time

$arr = array("1","5","6");

循环

$index[$arr[0]];

循环

$index["1"][$arr[1]]  // "1" since this key was filled in by the previous loop, continuing with a new key

循环

$index["1"]["5"][$arr[2]] // same as previous loop

--遍历所有 $arr 的项目,完成,结果为 $index["1"]["5"]["6"]--

--looped over all $arr's items, done, result is $index["1"]["5"]["6"]--

问题是我不知道 $arr 数组包含多少值.然后,我不知道如何继续,例如 $index["1"]$arr 的第一个值已循环到下一个数组时级别(换句话说:添加另一个键)..

The problem is I won't know how much values the $arr array contains. Then, I don't know how to continue from, for example, $index["1"] when the first value of $arr has been looped to the next array level (other words: add another key)..

有人吗?

推荐答案

您可以在此处使用参考资料:

You can use references here:

$a = array("1","5","6");
$b = array();
$c =& $b;

foreach ($a as $k) {
    $c[$k] = array();
    $c     =& $c[$k];
}

输出

Array 
    (
    [1] => Array
        (
            [5] => Array
                (
                    [6] => Array
                        (
                        )
                )
        )
)

要用其他值覆盖最后一个元素,您只需添加以下行:

To overwrite the last element with some other value, you can just add the line:

$c = 'blubber';

在循环之后,因为 $c 是对最深数组级别的引用,当循环结束时.

after the loop, because $c is a reference to the deepest array level, when the loop is finished.

相关文章