3v4l.org

run code in 300+ PHP versions simultaneously
<?php $a=array(array(207306,'Bob',''), array (199730,'Sam',199714), array(199728,'Simon',207306), array(199714,'John',207306), array(199716,'Tom',199718), array(199718,'Phillip',207306), array(199720,'James',207306)); # map the children by parent $parents = ['' => []]; foreach ($a as $val) { $parents[$val[2]][] = $val; } # start with those with no parent $sorted = $parents['']; # add the children the current nodes are parent of until the array is empty # a bit slower loop which works in all versions for ($val = reset($sorted); $val; $val = next($sorted)) { if (isset($parents[$val[0]])) { foreach ($parents[$val[0]] as $next) { $sorted[] = $next; } } } var_dump($sorted);
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(7) { [0]=> array(3) { [0]=> int(207306) [1]=> string(3) "Bob" [2]=> string(0) "" } [1]=> array(3) { [0]=> int(199728) [1]=> string(5) "Simon" [2]=> int(207306) } [2]=> array(3) { [0]=> int(199714) [1]=> string(4) "John" [2]=> int(207306) } [3]=> array(3) { [0]=> int(199718) [1]=> string(7) "Phillip" [2]=> int(207306) } [4]=> array(3) { [0]=> int(199720) [1]=> string(5) "James" [2]=> int(207306) } [5]=> array(3) { [0]=> int(199730) [1]=> string(3) "Sam" [2]=> int(199714) } [6]=> array(3) { [0]=> int(199716) [1]=> string(3) "Tom" [2]=> int(199718) } }
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(7) { [0]=> array(3) { [0]=> int(207306) [1]=> string(3) "Bob" [2]=> string(0) "" } [1]=> array(3) { [0]=> int(199728) [1]=> string(5) "Simon" [2]=> int(207306) } [2]=> array(3) { [0]=> int(199714) [1]=> string(4) "John" [2]=> int(207306) } [3]=> array(3) { [0]=> int(199718) [1]=> string(7) "Phillip" [2]=> int(207306) } [4]=> array(3) { [0]=> int(199720) [1]=> string(5) "James" [2]=> int(207306) } [5]=> array(3) { [0]=> int(199730) [1]=> string(3) "Sam" [2]=> int(199714) } [6]=> array(3) { [0]=> int(199716) [1]=> string(3) "Tom" [2]=> int(199718) } }

preferences:
223.97 ms | 403 KiB | 300 Q