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

PHP One level deeper in array each loop made(PHP 每个循环在数组中更深一层)
本文介绍了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 每个循环在数组中更深一层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)