Php 将MPTT结果集排序到多维数组中
我一直在试验改进的预排序树遍历 模式,我的测试用例代码将返回预期的结果 无法将二维数组转换为多维数组以显示它 这是一个3级菜单结果的示例,我需要将其转换为多维数组,以便在TAL中迭代它:Php 将MPTT结果集排序到多维数组中,php,zend-db,mptt,Php,Zend Db,Mptt,我一直在试验改进的预排序树遍历 模式,我的测试用例代码将返回预期的结果 无法将二维数组转换为多维数组以显示它 这是一个3级菜单结果的示例,我需要将其转换为多维数组,以便在TAL中迭代它: Array ( [0] => Array ( [CategoryID] => 1 [ParentID] => 0 [CategoryName] => Default Parent
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
)
)
我需要对数据进行结构化,以便每个父级都有一个“Children”键,它是一个重复的数组数组,不限制父级/子级/孙级可以拥有的子级数量,树深度键由DBMS自动计算出来,因此我只需更改数组的结构
非常感谢任何指针,我使用usort()和array\u walk\u recursive都没有用
提前感谢我认为一个简单的foreach就可以做到这一点(在参考资料的帮助下): 设置
$菜单
关联数组$cat\u id=>$element\u details\u anb\u子项
:
$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
数组已排序(即父数组在其子数组之前)时,它才起作用。完美,而不是一个小错误:if(isset($ref[$d['ParentID']]){应该是:if(isset($ref[$d['ParentID']){非常感谢!