3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?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);
based on PPQYD
Output for 5.6.30, hhvm-3.18.5 - 3.22.0, 7.0.30 - 7.3.0alpha1
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 ) ) ) ) ) )