从Codeigniter中的平面数组构建树

时间:2019-06-05 05:59:00

标签: php codeigniter-3

我环顾了互联网,但还没有完全找到我想要的东西。我有一个平面数组,每个元素包含一个“ id”和一个“ parent_id”。每个元素只有一个父元素,但可能有多个子元素。如果parent_id = 0,则将其视为根级项目。我正在尝试将平面阵列变成一棵树。我发现的示例仅适用于核心php。因为在codeigniter中,递归并不繁琐

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

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

我的平面数组是

Array
(
    [1] => Array
        (
            [id] => 1
            [parent_id] => 0
            [permission_category] => Listing

    [3] => Array
        (
            [id] => 3
            [parent_id] => 1
            [permission_category] => Tour
        )

    [4] => Array
        (
            [id] => 4
            [parent_id] => 1
            [permission_category] => Activity
        )

    [12] => Array
        (
            [id] => 12
            [parent_id] => 0
            [permission_category] => Bookings
            [parent_permission_category] => 
        )

    [13] => Array
        (
            [id] => 13
            [parent_id] => 12
            [permission_category] => Activity Bookings
        )

    [14] => Array
        (
            [id] => 14
            [parent_id] => 12
            [permission_category] => Tour Bookings
        )

);

它只显示一个父母的孩子

Array
(
    [1] => Array
        (
            [id] => 1
            [parent_id] => 0
            [permission_category] => Listing
            [children] => Array
                (

                    [3] => Array
                        (
                            [id] => 3
                            [parent_id] => 1
                            [permission_category] => Tour
                        )

                    [4] => Array
                        (
                            [id] => 4
                            [parent_id] => 1
                            [permission_category] => Activity
                        )
                )

        )

)

0 个答案:

没有答案