PHP走过,而preserving键多维数组 [英] PHP Walk through multidimensional array while preserving keys

查看:158
本文介绍了PHP走过,而preserving键多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组,而我不知道深浅。该阵列例如可以是这样的:

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',
);

随着这阵我想创建一个目录。这意味着钥匙需preserved因为我利用他们作为章节编号。例如,testvalue1是章1.5.3。

现在,我想在preserving所有按键通过数组走路 - 不使用array_walk_recursive含有另一个数组键被丢弃(?正确的)和preferably不使用考虑速度嵌套foreach循环

任何建议我应该怎么做呢?先谢谢了。


PS:对于我的脚本不如果密钥字符串(1而不是1)或整数,如果有字符串作为关键会使array_walk_recursive preserve他们没关系

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.

推荐答案

您可以在您的阵列迭代用栈的帮助下建立自己的TOC。

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 行不通的,因为它不会给你的父元素(S)的钥匙。请参阅此相关的问题还有:<一href=\"http://stackoverflow.com/questions/7011451/transa$p$pntly-flatten-an-array/7011675\">Transparently扁平化数组,它有一个很好的答案,是比较通用的情况下,也非常有帮助。

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走过,而preserving键多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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