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);

preferences:
29.29 ms | 402 KiB | 5 Q