3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $arr = [ 0=>['id'=>1,'name'=>'父1','father'=>0], 1=>['id'=>2,'name'=>'父2','father'=>0], 2=>['id'=>3,'name'=>'父3','father'=>0], 3=>['id'=>4,'name'=>'儿1-1','father'=>1], 4=>['id'=>5,'name'=>'儿1-2','father'=>1], 5=>['id'=>6,'name'=>'儿1-3','father'=>1], 6=>['id'=>7,'name'=>'儿2-1','father'=>2], 7=>['id'=>8,'name'=>'儿2-1','father'=>2], 8=>['id'=>9,'name'=>'儿3-1','father'=>3], 9=>['id'=>10,'name'=>'儿3-1-1','father'=>9], 10=>['id'=>11,'name'=>'儿1-1-1','father'=>4], 11=>['id'=>12,'name'=>'儿2-1-1','father'=>7], ]; function generateTree($arr,$id,$step){ static $tree=[]; foreach($arr as $key=>$val) { if($val['father'] == $id) { $flg = str_repeat('└―',$step); $val[$val['id']] = $flg.$val['name']; $tree[$val['id']] = $val; generateTree($arr , $val['id'] ,$step+1); } } return $tree; } $tree = generateTree($arr,0,0); foreach ($tree as $val){ $new[] = $val['name'].'<br>'; } print_r($new);
based on o9c21
Output for 5.6.30, hhvm-3.18.5 - 3.22.0, 7.0.30 - 7.3.0alpha1
Array ( [0] => 父1<br> [1] => 儿1-1<br> [2] => 儿1-1-1<br> [3] => 儿1-2<br> [4] => 儿1-3<br> [5] => 父2<br> [6] => 儿2-1<br> [7] => 儿2-1-1<br> [8] => 儿2-1<br> [9] => 父3<br> [10] => 儿3-1<br> [11] => 儿3-1-1<br> )