3v4l.org

run code in 300+ PHP versions simultaneously
<?php // use ORDER BY belongs_to DESC, id ASC ... or usort() to prepare result set $resultset = [ ['id' => '6a', 'belongs_to' => '5a'], ['id' => '5a', 'belongs_to' => '3a'], ['id' => '8a', 'belongs_to' => '3a'], ['id' => '3a', 'belongs_to' => '1a'], ['id' => '1a', 'belongs_to' => null], ['id' => '2a', 'belongs_to' => null], ['id' => '4a', 'belongs_to' => null], ['id' => '7a', 'belongs_to' => null] ]; foreach ($resultset as $index1 => &$row1) { // make input array modifiable by reference (not working with a copy) if ($row1['belongs_to']) { // original belongs_to value is not null (not a top-level parent) foreach ($resultset as $index2 => $row2) { // search for targeted parent if ($row2['id'] == $row1['belongs_to']) { // parent found $resultset[$index2]['children'][] = [$row1['id'] => $row1['children'] ?? []]; // store original row as child unset($resultset[$index1]); // remove original row (no reason to iterate it again in outer loop) break; // halt inner loop (no reason to iterate further) } } } else { // original belongs_to value is null (top-level parent) $output[$row1['id']] = $row1['children'] ?? []; // store children to top } } var_export($output);
Output for 7.1.0 - 7.1.23, 7.2.0 - 7.2.33, 7.3.16 - 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 ( '1a' => array ( 0 => array ( '3a' => array ( 0 => array ( '5a' => array ( 0 => array ( '6a' => array ( ), ), ), ), 1 => array ( '8a' => array ( ), ), ), ), ), '2a' => array ( ), '4a' => array ( ), '7a' => 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 ( '1a' => array ( 0 => array ( '3a' => array ( 0 => array ( '5a' => array ( 0 => array ( '6a' => array ( ), ), ), ), 1 => array ( '8a' => array ( ), ), ), ), ), '2a' => array ( ), '4a' => array ( ), '7a' => array ( ), )
Output for 5.6.38
Parse error: syntax error, unexpected '?' in /in/97S5I on line 18
Process exited with code 255.

preferences:
189.03 ms | 401 KiB | 173 Q