PHP 每个循环在数组中更深一层 [英] PHP One level deeper in array each loop made

查看:20
本文介绍了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.

这篇关于PHP 每个循环在数组中更深一层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆