我正在尝试设置一个可以有多个级别的列表,使用parentId来定义其父级.第一项的parentId为NULL.一些条目的示例:
id parentId name 1 NULL item1 2 NULL item2 3 1 item3 4 2 item4 5 3 item5 6 3 item6
所以,1和2是主要项目; 3是1的孩子; 4是2的孩子; 5是3的孩子(1本身的孩子); 6也是3的孩子(自己是1的孩子);等等
我无法创建一个正确添加这些项目到正确级别的数组.它应该如下所示:
Array ( [1] => Array ( [name] => item1 [parentId] => [children] => Array ( [3] => Array ( [name] => item3 [parentId] => 1 [children] => Array ( [5] => Array ( [name] => item5 [parentId] => 3 ) [6] => Array ( [name] => item6 [parentId] => 3 ) ) ) ) ) [2] => Array ( [name] => item2 [parentId] => [children] => Array ( [4] => Array ( [name] => item4 [parentId] => 2 ) ) ) )
但是说我使用foreach()遍历所有项目,然后我到达第5项.它的parentId是3,但是那时,我不知道这个父3在数组中的位置,以及如何添加子项那个父母.
是否有一个技巧循环这些项目,并以正确的方式将它们全部放在适当的位置?
开始
原文链接:https://www.f2er.com/php/134826.html// your original data as an array $data = array( array( 'id' => 1,'parentId' => null,'name' => 'item1' ),array( 'id' => 2,'name' => 'item2' ),array( 'id' => 3,'parentId' => 1,'name' => 'item3' ),array( 'id' => 4,'parentId' => 2,'name' => 'item4' ),array( 'id' => 5,'parentId' => 3,'name' => 'item5' ),array( 'id' => 6,'name' => 'item6' ),);
递归函数
function buildTree( $ar,$pid = null ) { $op = array(); foreach( $ar as $item ) { if( $item['parentId'] == $pid ) { $op[$item['id']] = array( 'name' => $item['name'],'parentId' => $item['parentId'] ); // using recursion $children = buildTree( $ar,$item['id'] ); if( $children ) { $op[$item['id']]['children'] = $children; } } } return $op; } print_r( buildTree( $data ) ); /* Array ( [1] => Array ( [name] => item1 [parentId] => [children] => Array ( [3] => Array ( [name] => item3 [parentId] => 1 [children] => Array ( [5] => Array ( [name] => item5 [parentId] => 3 ) [6] => Array ( [name] => item6 [parentId] => 3 ) ) ) ) ) [2] => Array ( [name] => item2 [parentId] => [children] => Array ( [4] => Array ( [name] => item4 [parentId] => 2 ) ) ) ) */