如何使用父索引列出所有多维数组

时间:2017-10-02 06:39:14

标签: php arrays arraylist multidimensional-array

如何使用父索引列出所有多维数组。每个级别的所有索引都是唯一的,我想显示所有级别的列表。

示例我的数组:

 Array(
[1] => Array(
        [2] => Array(
                [3] => 
                [4] => 
                [7] => 
            )
    )

[6] => Array(
        [11] => Array(
                [12] =>  Array(
                         [17] => 
                        )
            )
    )

[2] => Array(
        [13] => Array(
                [14] => 
            )

    )
 )

我想得到这样的输出:

Array
(
 [1]=array([level] = 1)
 [2]=array([level] = 2)
 [3]=array([level] = 3)
 [4]=array([level] = 3)
 [7]=array([level] = 3)
 [6]=array([level] = 1)
 [11]=array([level] = 2)
 [12]=array([level] = 3)
 [17]=array([level] = 4)
 ...
 )

1 个答案:

答案 0 :(得分:0)

以下是使用recursive函数的解决方案。如果没有更多子/嵌套数组,假设您的array将具有NULL值。

$arr = array(1 => array(2 => array(3 => NULL, 
                                       4 => NULL,
                                       7 => NULL )),
             6 => array(11 => array(12 =>  array(17 =>NULL))),
             2 => array(13 => array(14 => NULL)));

$rslt_arr = array();

function traverse_arr($array, $level)
{
    $level++;
    foreach ($array as $key => $value){
        if($value != NULL){
            traverse_arr($value, $level);
        }
        $GLOBALS['rslt_arr'][$key]['level'] = $level;
    }
}

traverse_arr($arr, 0);

echo '<pre>';
print_r($rslt_arr);

<强>输出:

Array
(
    [3] => Array
        (
            [level] => 3
        )

    [4] => Array
        (
            [level] => 3
        )

    [7] => Array
        (
            [level] => 3
        )

    [2] => Array
        (
            [level] => 1
        )

    [1] => Array
        (
            [level] => 1
        )

    [17] => Array
        (
            [level] => 4
        )

    [12] => Array
        (
            [level] => 3
        )

    [11] => Array
        (
            [level] => 2
        )

    [6] => Array
        (
            [level] => 1
        )

    [14] => Array
        (
            [level] => 3
        )

    [13] => Array
        (
            [level] => 2
        )

)