创建递归嵌套数组

时间:2017-06-26 11:54:08

标签: php arrays multidimensional-array

我想基于key创建多维数组。

下面是我原来的数组。

原始阵列。

Array
(
    [13] => Array
        (
            [member_id] => 13
            [parent_id] => 0
        )

    [14] => Array
        (
            [member_id] => 14
            [parent_id] => 13
        )

    [15] => Array
        (
            [member_id] => 15
            [parent_id] => 14
        )

)
  

注意:提供的数组是静态的,但它是动态的。

必填数据

Array
(
    [13] => Array
        (
            [member_id] => 13
            [parent_id] => 0
            [14] => Array
            (
                [member_id] => 14
                [parent_id] => 13
                [15] => Array
                (
                    [member_id] => 15
                    [parent_id] => 14
                )
            )
        )
)

感谢。

1 个答案:

答案 0 :(得分:0)

<强> PHP

function buildTree(array $elements, $parentId = 0) {
    $branch = array();

    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = buildTree($elements, $element['member_id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }

    return $branch;
}

$tree = buildTree($output);

<强>输出

Array
(
    [13] => Array
        (
            [member_id] => 13
            [parent_id] => 0
            [children] => Array
            (
                [0] => Array
                (
                    [member_id] => 14
                    [parent_id] => 13
                    [children] => Array
                    (
                        [0] => Array
                        (
                            [member_id] => 15
                            [parent_id] => 14
                        )
                    )
                )
            )
        )
)