1

我一直在尝试修改的预排序树遍历模式,我的测试用例代码按预期返回结果,但是我无法将二维数组转换为多维数组来呈现它。

这是一个 3 级菜单结果的示例,我需要将其转换为多维数组,以便可以在 TAL 中对其进行迭代:

Array
(
    [0] => Array
        (
            [CategoryID] => 1
            [ParentID] => 0
            [CategoryName] => Default Parent
            [lt] => 1
            [rt] => 14
            [tree_depth] => 1
        )

    [1] => Array
        (
            [CategoryID] => 8
            [ParentID] => 1
            [CategoryName] => SysAdmin
            [lt] => 2
            [rt] => 7
            [tree_depth] => 2
        )

    [2] => Array
        (
            [CategoryID] => 2
            [ParentID] => 8
            [CategoryName] => Linux
            [lt] => 3
            [rt] => 4
            [tree_depth] => 3
        )

    [3] => Array
        (
            [CategoryID] => 3
            [ParentID] => 8
            [CategoryName] => Windows
            [lt] => 5
            [rt] => 6
            [tree_depth] => 3
        )

    [4] => Array
        (
            [CategoryID] => 5
            [ParentID] => 1
            [CategoryName] => Code
            [lt] => 8
            [rt] => 13
            [tree_depth] => 2
        )

    [5] => Array
        (
            [CategoryID] => 6
            [ParentID] => 5
            [CategoryName] => PHP
            [lt] => 9
            [rt] => 10
            [tree_depth] => 3
        )

    [6] => Array
        (
            [CategoryID] => 7
            [ParentID] => 5
            [CategoryName] => Perl
            [lt] => 11
            [rt] => 12
            [tree_depth] => 3
        )

)

我需要对数据进行结构化,以便每个父母都有一个“孩子”键,它是一个重复的数组数组,对父母/孩子/孙子可以拥有的孩子数量没有限制,tree_depth 键由DBMS,所以我只需要改变数组的结构。

非常感谢任何指针,我玩过 usort() 和 array_walk_recursive 无济于事。

提前致谢

4

1 回答 1

3

我认为一个简单的foreach方法可以做到这一点(在参考资料的帮助下):

设置$menu关联数组$cat_id => $element_details_anb_children

$menu = array(); $ref = array();
foreach( $tree as $d ) {
    $d['children'] = array();
    if( isset( $ref[ $d['ParentID'] ] ) ) { // we have a reference on its parent
        $ref[ $d['ParentID'] ]['children'][ $d['CategoryID'] ] = $d;
        $ref[ $d['CategoryID'] ] =& $ref[ $d['ParentID'] ]['children'][ $d['CategoryID'] ];
    } else { // we don't have a reference on its parent => put it a root level
        $menu[ $d['CategoryID'] ] = $d;
        $ref[ $d['CategoryID'] ] =& $menu[ $d['CategoryID'] ];
    }
}

这应该构建两个数组:您想要的多维数组 ( $menu) 和一个仅包含每个类别的引用的平面数组。在每次迭代中,如果它已经存在,它会将类别嵌套到其父级中(这就是我保留参考表的原因)。当然,它只有在您的初始$tree数组是有序的(即父级在其子级之前)时才有效。

于 2009-06-22T13:03:31.623 回答