PHP 遍历多维数组同时保留键
我有一个多维数组,我不知道其深度。例如,该数组可能如下所示:
$array = array(
1 => array(
5 => array(
3 => 'testvalue1'
)
),
2 => array(
6 => 'testvalue2'
),
3 => 'testvalue3',
4 => 'testvalue4',
);
我想使用该数组创建一个目录。这意味着需要保留密钥,因为我将它们用作“章节编号”。例如,“testvalue1”位于第 1.5.3 章中。
现在我想遍历数组,同时保留所有键 - 不使用 array_walk_recursive,因为包含另一个数组的键被删除(正确?),考虑到速度,最好不使用嵌套的 foreach 循环。
有什么建议我应该如何做到这一点?提前致谢。
PS:对于我的脚本来说,键是字符串(“1”而不是 1)还是整数并不重要,如果将字符串作为键将使 array_walk_recursive 保留它们。
I've got a multidimensional array of which I can't know the depth. The array could for example look like this:
$array = array(
1 => array(
5 => array(
3 => 'testvalue1'
)
),
2 => array(
6 => 'testvalue2'
),
3 => 'testvalue3',
4 => 'testvalue4',
);
With this array I want to create a table of contents. That means the keys need to be preserved as I'm using them as "chapter numbers". For example, "testvalue1" is in chapter 1.5.3.
Now I want to walk through the array while preserving all keys - not using array_walk_recursive as the keys containing another array are dropped (correct?) and preferably not using nested foreach loops considering the speed.
Any suggestions how I should do this? Thanks in advance.
PS: For my script it doesn't matter if the keys are strings ("1" instead of 1) or integers, if having strings as key will make array_walk_recursive preserve them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以借助堆栈迭代数组来构建目录。
输出:
如果需要,您也可以另外处理该级别,但这从您的问题中并不清楚。
array_walk_recursive
不起作用,因为它不会为您提供父元素的键。另请参阅此相关问题:Transparently flatten an array,它有一个很好的答案并且对于更一般的情况也很有帮助。You can iterate over your array with a help of a stack to build your toc.
Output:
You can additionally handle the level as well if you need to, but that was not clear from your question.
array_walk_recursive
does not work, because it won't give you the keys of the parent element(s). See this related question as well: Transparently flatten an array, it has a good answer and is helpful for more generic cases as well.http://codepad.org/4l4385MZ
http://codepad.org/4l4385MZ
试试这个:
Try this:
另一种最适合我处理深层嵌套多维关联和非关联数组的方法:
将其与大型多维数组一起使用将输出如下内容:
Another take on this that worked best for me with handling deep nested multidimensional associative and non-associative arrays:
Using it with a large multidimensional array will output something like this: