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

时间:2020-12-31 20:21:10

I have the following array on a hierarchy structure - It's basically an array with categories and its children under the 'child' key:

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

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
                                            (
                                            )

                                     )
                            )

                    )
            )
    )

What I am trying to do is write a recursive function to reorganize this array as an ONE LEVEL array only. Instead of having its children inside the 'child' key, I want it to be part of the array root level. Like this:

我想要做的是写一个递归函数来重新组织这个数组只作为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
    )

Any ideas?

有任何想法吗?

Thanks!

谢谢!

1 个解决方案

#1


1  

The following recursive function should serve your purpose:

以下递归函数应该用于您的目的:

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

DEMO

#1


1  

The following recursive function should serve your purpose:

以下递归函数应该用于您的目的:

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

DEMO