3v4l.org

run code in 300+ PHP versions simultaneously
<?php function make_recursive($arr, $root = 0, $pid = 'pid', $id = 'id', $child = 'child') { $m = array(); foreach ($arr as $e) { if (!isset($m[$e[$pid]])) $m[$e[$pid]] = array(); if (!isset($m[$e[$id]])) $m[$e[$id]] = array(); $m[$e[$pid]][] = array_merge($e, array($child => &$m[$e[$id]])); } return $m[$root][0]; } $arr = array( array('id' => 5273, 'pid' => 0, 'name' => 'John Doe'), array('id' => 6032, 'pid' => 5273, 'name' => 'Sally Smith'), array('id' => 6034, 'pid' => 6032, 'name' => 'Mike Jones'), array('id' => 6035, 'pid' => 6034, 'name' => 'Jason Williams'), array('id' => 6036, 'pid' => 5273, 'name' => 'Sara Johnson'), array('id' => 6037, 'pid' => 5273, 'name' => 'Dave Wilson'), array('id' => 6038, 'pid' => 6037, 'name' => 'Amy Martin'), ); $re=make_recursive($arr); var_export($re);
Output for 7.0.0 - 7.0.25, 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 ( 'id' => 5273, 'pid' => 0, 'name' => 'John Doe', 'child' => array ( 0 => array ( 'id' => 6032, 'pid' => 5273, 'name' => 'Sally Smith', 'child' => array ( 0 => array ( 'id' => 6034, 'pid' => 6032, 'name' => 'Mike Jones', 'child' => array ( 0 => array ( 'id' => 6035, 'pid' => 6034, 'name' => 'Jason Williams', 'child' => array ( ), ), ), ), ), ), 1 => array ( 'id' => 6036, 'pid' => 5273, 'name' => 'Sara Johnson', 'child' => array ( ), ), 2 => array ( 'id' => 6037, 'pid' => 5273, 'name' => 'Dave Wilson', 'child' => array ( 0 => array ( 'id' => 6038, 'pid' => 6037, 'name' => 'Amy Martin', 'child' => array ( ), ), ), ), ), )
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 ( 'id' => 5273, 'pid' => 0, 'name' => 'John Doe', 'child' => array ( 0 => array ( 'id' => 6032, 'pid' => 5273, 'name' => 'Sally Smith', 'child' => array ( 0 => array ( 'id' => 6034, 'pid' => 6032, 'name' => 'Mike Jones', 'child' => array ( 0 => array ( 'id' => 6035, 'pid' => 6034, 'name' => 'Jason Williams', 'child' => array ( ), ), ), ), ), ), 1 => array ( 'id' => 6036, 'pid' => 5273, 'name' => 'Sara Johnson', 'child' => array ( ), ), 2 => array ( 'id' => 6037, 'pid' => 5273, 'name' => 'Dave Wilson', 'child' => array ( 0 => array ( 'id' => 6038, 'pid' => 6037, 'name' => 'Amy Martin', 'child' => array ( ), ), ), ), ), )

preferences:
226.14 ms | 404 KiB | 225 Q