function buildTree($array,$parentId){
$tree = array();
foreach ($array as $item) {
if ($item['parent_id'] == $parentId) {
$data=$this-> buildTree($array, $item['id']);
if(empty($data)){
$tree[]=$item['id'];
}else{
$tree[]=$item['id'];
$tree=array_merge($tree,$data);
}
}
}
return $tree;
}
$array = [
['id' => 1, 'parent_id' => 0, 'name' => 'Root 1'],
['id' => 2, 'parent_id' => 0, 'name' => 'Root 2'],
['id' => 3, 'parent_id' => 1, 'name' => 'Child 1'],
['id' => 4, 'parent_id' => 1, 'name' => 'Child 2'],
['id' => 5, 'parent_id' => 2, 'name' => 'Child 3'],
['id' => 6, 'parent_id' => 4, 'name' => 'Grandchild 1'],
];
$data =buildTree($array, 1);
var_dump($data);
// 打印是
array(3) {
[0] => int(3)
[1] => int(4)
[2] => int(6)
}
function buildTree(array $array, $parentId = 0)
{
$tree = array();
foreach ($array as $item) {
if ($item['parent_id'] == $parentId) {
$children = buildTree($array, $item['id']);
if ($children) {
$item['children'] = $children;
}
$tree[] = $item;
}
}
return $tree;
}
$array = [
['id' => 1, 'parent_id' => 0, 'name' => 'Root 1'],
['id' => 2, 'parent_id' => 0, 'name' => 'Root 2'],
['id' => 3, 'parent_id' => 1, 'name' => 'Child 1'],
['id' => 4, 'parent_id' => 1, 'name' => 'Child 2'],
['id' => 5, 'parent_id' => 2, 'name' => 'Child 3'],
['id' => 6, 'parent_id' => 4, 'name' => 'Grandchild 1'],
];
$tree = buildTree($array);
print_r($tree);
// 打印
Array
(
[0] => Array
(
[id] => 1
[parent_id] => 0
[name] => Root 1
[children] => Array
(
[0] => Array
(
[id] => 3
[parent_id] => 1
[name] => Child 1
)
[1] => Array
(
[id] => 4
[parent_id] => 1
[name] => Child 2
[children] => Array
(
[0] => Array
(
[id] => 6
[parent_id] => 4
[name] => Grandchild 1
)
)
)
)
)
[1] => Array
(
[id] => 2
[parent_id] => 0
[name] => Root 2
[children] => Array
(
[0] => Array
(
[id] => 5
[parent_id] => 2
[name] => Child 3
)
)
)
)