PHP 在保留键的同时遍历多维数组 [英] PHP Walk through multidimensional array while preserving keys
问题描述
我有一个不知道深度的多维数组.例如,该数组可能如下所示:
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',
);
我想用这个数组创建一个目录.这意味着需要保留密钥,因为我将它们用作章节编号".例如,testvalue1"在第 1.5.3 章中.
现在我想遍历数组,同时保留所有键 - 不使用 array_walk_recursive 因为包含另一个数组的键被删除(正确?),并且考虑到速度最好不使用嵌套的 foreach 循环.
任何建议我应该如何做到这一点?提前致谢.
PS:对于我的脚本,键是字符串(1"而不是 1)还是整数并不重要,如果将字符串作为键将使 array_walk_recursive 保留它们.
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.
推荐答案
您可以在堆栈的帮助下迭代您的数组以构建您的目录.
You can iterate over your array with a help of a stack to build your toc.
$stack = &$array;
$separator = '.';
$toc = array();
while ($stack) {
list($key, $value) = each($stack);
unset($stack[$key]);
if (is_array($value)) {
$build = array($key => ''); # numbering without a title.
foreach ($value as $subKey => $node)
$build[$key . $separator . $subKey] = $node;
$stack = $build + $stack;
continue;
}
$toc[$key] = $key. ' ' . $value;
}
print_r($toc);
输出:
Array
(
[1] => 1
[1.5] => 1.5
[1.5.3] => 1.5.3 testvalue1
[2] => 2
[2.6] => 2.6 testvalue2
[3] => 3 testvalue3
[4] => 4 testvalue4
)
如果需要,您也可以另外处理该级别,但这从您的问题中不清楚.
You can additionally handle the level as well if you need to, but that was not clear from your question.
array_walk_recursive
不起作用,因为它不会给你父元素的键.也请参阅此相关问题:透明地展平数组,它有一个很好的答案并且对于更通用的情况也有帮助.
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.
这篇关于PHP 在保留键的同时遍历多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!