PHP One level deeper in array each loop made(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 每个循环在数组中更深一层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 每个循环在数组中更深一层
基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
