子节点移动到层次结构数组上的根级别

时间:2014-02-26 01:31:17

标签: php arrays recursion tree hierarchy

我在层次结构上有以下数组 - 它基本上是一个包含类别及其子项位于“子”键下的数组:

Array
    (
        [category_id] => 1
        [parent_id] => 0
        [name] => Commercial
        [child] => Array
            (
                [0] => Array
                    (
                        [category_id] => 48
                        [parent_id] => 1
                        [name] => lights
                        [child] => Array
                            (
                            )
                    )

                [1] => Array
                    (
                        [category_id] => 12
                        [parent_id] => 1
                        [name] => beacons
                        [child] => Array
                            (
                                [0] => Array
                                    (
                                        [category_id] => 91
                                        [parent_id] => 12
                                        [name] => blue beacons
                                        [child] => Array
                                            (
                                            )

                                     )
                            )

                    )
            )
    )

我要做的是编写一个递归函数,仅将此数组重新组织为ONE LEVEL数组。我希望它成为数组根级别的一部分,而不是将其子项放在“子”键中。像这样:

[0] => Array
    (
        [category_id] => 1
        [parent_id] => 0
        [name] => Commercial
    )

[1] => Array
    (
        [category_id] => 48
        [parent_id] => 1
        [name] => lights
    )

[2] => Array
    (
        [category_id] => 12
        [parent_id] => 1
        [name] => beacons
    )


[3] => Array
    (
        [category_id] => 91
        [parent_id] => 12
        [name] => blue beacons
    )

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

以下递归函数应该符合您的目的:

function one_level_array($arr){
$ret = array();
$ret[] = array_diff_key($arr, array("child" => ""));
    if(array_key_exists("child", $arr)){
        foreach($arr["child"] as $child){
        $ret = array_merge($ret, one_level_array($child));
        }
    }
return $ret;
}

DEMO