3v4l.org

run code in 300+ PHP versions simultaneously
<?php function findParent(&$array,$whos_your_daddy=0,$baby=[]){ // make $array modifiable foreach($array as $i=>&$row){ // make $row modifiable if($whos_your_daddy){ if($row['id']==$whos_your_daddy){ // found parent $row['nodes'][]=$baby; }elseif(isset($row['nodes'])){ // go down rabbit hole looking for parent findParent($row['nodes'],$whos_your_daddy,$baby); } }elseif($row['parent_id']){ // child requires adoption unset($array[$i]); // remove child from level because it will be store elsewhere and won't be its own parent (reduce iterations in next loop & avoid infinite recursion) findParent($array,$row['parent_id'],$row); } } return $array; } // $db->query('SELECT id,name_a AS name,parent_id FROM accounts_tree ORDER BY id'); // for($resultset=[]; $row=$res->fetch_assoc(); $resultset[]=$row); // inspired by: http://php.net/manual/en/mysqli-result.fetch-assoc.php#112924 $resultset=[ ['id'=>1,'name'=>'folder 1','parent_id'=>0], ['id'=>2,'name'=>'folder 2','parent_id'=>0], ['id'=>3,'name'=>'sub 1-1','parent_id'=>1], ['id'=>4,'name'=>'sub 2-1','parent_id'=>2], ['id'=>5,'name'=>'Sub 1-1-1','parent_id'=>3], ['id'=>6,'name'=>'folder 3','parent_id'=>0], ['id'=>7,'name'=>'sub 1-1-1-1','parent_id'=>5] ]; print_r(findParent($resultset));
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.34, 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] => folder 1 [parent_id] => 0 [nodes] => Array ( [0] => Array ( [id] => 3 [name] => sub 1-1 [parent_id] => 1 [nodes] => Array ( [0] => Array ( [id] => 5 [name] => Sub 1-1-1 [parent_id] => 3 [nodes] => Array ( [0] => Array ( [id] => 7 [name] => sub 1-1-1-1 [parent_id] => 5 ) ) ) ) ) ) ) [1] => Array ( [id] => 2 [name] => folder 2 [parent_id] => 0 [nodes] => Array ( [0] => Array ( [id] => 4 [name] => sub 2-1 [parent_id] => 2 ) ) ) [5] => Array ( [id] => 6 [name] => folder 3 [parent_id] => 0 ) )
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] => folder 1 [parent_id] => 0 [nodes] => Array ( [0] => Array ( [id] => 3 [name] => sub 1-1 [parent_id] => 1 [nodes] => Array ( [0] => Array ( [id] => 5 [name] => Sub 1-1-1 [parent_id] => 3 [nodes] => Array ( [0] => Array ( [id] => 7 [name] => sub 1-1-1-1 [parent_id] => 5 ) ) ) ) ) ) ) [1] => Array ( [id] => 2 [name] => folder 2 [parent_id] => 0 [nodes] => Array ( [0] => Array ( [id] => 4 [name] => sub 2-1 [parent_id] => 2 ) ) ) [5] => Array ( [id] => 6 [name] => folder 3 [parent_id] => 0 ) )

preferences:
219.39 ms | 409 KiB | 300 Q