3v4l.org

run code in 300+ PHP versions simultaneously
<?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; generateTree($arr , $val['id'] ,$step+1); } } return $tree; } $tree = generateTree($arr,0,0); foreach ($tree as $val){ $new[] = $val['name'].'<br>'; } print_r($new);
Output for 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] => 父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> )
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] => 父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> )

preferences:
180.02 ms | 402 KiB | 192 Q