<?php
$arr = [
1=>['id'=>1,'name'=>'父1','father'=>NULL],
2=>['id'=>2,'name'=>'父2','father'=>NULL],
3=>['id'=>3,'name'=>'父3','father'=>NULL],
4=>['id'=>4,'name'=>'儿1-1','father'=>1],
5=>['id'=>5,'name'=>'儿1-2','father'=>1],
6=>['id'=>6,'name'=>'儿1-3','father'=>1],
7=>['id'=>7,'name'=>'儿2-1','father'=>2],
8=>['id'=>8,'name'=>'儿2-1','father'=>2],
9=>['id'=>9,'name'=>'儿3-1','father'=>3],
10=>['id'=>10,'name'=>'儿3-1-1','father'=>9],
11=>['id'=>11,'name'=>'儿1-1-1','father'=>4],
12=>['id'=>12,'name'=>'儿2-1-1','father'=>7],
];
function generateTree($items){
$tree = array();
foreach($items as $item){
if(isset($items[$item['father']])){
$items[$item['father']]['son'][$item['id']] = &$items[$item['id']];
}else{
$tree[] = &$items[$item['id']];
}
}
return $tree;
}
$tree = generateTree($arr);
print_r($tree);
- Output for 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
- Array
(
[0] => Array
(
[id] => 1
[name] => 父1
[father] =>
[son] => Array
(
[4] => Array
(
[id] => 4
[name] => 儿1-1
[father] => 1
[son] => Array
(
[11] => Array
(
[id] => 11
[name] => 儿1-1-1
[father] => 4
)
)
)
[5] => Array
(
[id] => 5
[name] => 儿1-2
[father] => 1
)
[6] => Array
(
[id] => 6
[name] => 儿1-3
[father] => 1
)
)
)
[1] => Array
(
[id] => 2
[name] => 父2
[father] =>
[son] => Array
(
[7] => Array
(
[id] => 7
[name] => 儿2-1
[father] => 2
[son] => Array
(
[12] => Array
(
[id] => 12
[name] => 儿2-1-1
[father] => 7
)
)
)
[8] => Array
(
[id] => 8
[name] => 儿2-1
[father] => 2
)
)
)
[2] => Array
(
[id] => 3
[name] => 父3
[father] =>
[son] => Array
(
[9] => Array
(
[id] => 9
[name] => 儿3-1
[father] => 3
[son] => Array
(
[10] => Array
(
[id] => 10
[name] => 儿3-1-1
[father] => 9
)
)
)
)
)
)
- Output for 8.3.5
- Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Array
(
[0] => Array
(
[id] => 1
[name] => 父1
[father] =>
[son] => Array
(
[4] => Array
(
[id] => 4
[name] => 儿1-1
[father] => 1
[son] => Array
(
[11] => Array
(
[id] => 11
[name] => 儿1-1-1
[father] => 4
)
)
)
[5] => Array
(
[id] => 5
[name] => 儿1-2
[father] => 1
)
[6] => Array
(
[id] => 6
[name] => 儿1-3
[father] => 1
)
)
)
[1] => Array
(
[id] => 2
[name] => 父2
[father] =>
[son] => Array
(
[7] => Array
(
[id] => 7
[name] => 儿2-1
[father] => 2
[son] => Array
(
[12] => Array
(
[id] => 12
[name] => 儿2-1-1
[father] => 7
)
)
)
[8] => Array
(
[id] => 8
[name] => 儿2-1
[father] => 2
)
)
)
[2] => Array
(
[id] => 3
[name] => 父3
[father] =>
[son] => Array
(
[9] => Array
(
[id] => 9
[name] => 儿3-1
[father] => 3
[son] => Array
(
[10] => Array
(
[id] => 10
[name] => 儿3-1-1
[father] => 9
)
)
)
)
)
)
preferences:
230.12 ms | 409 KiB | 284 Q