3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array = array(array('table' => 'test', 'parent_table' => NULL), array('table' => 'test', 'parent_table' => NULL), array('table' => 'test2', 'parent_table' => 'test'), array('table' => 'test4', 'parent_table' => NULL), array('table' => 'test5', 'parent_table' => 'test3'), array('table' => 'test6', 'parent_table' => 'test5'), array('table' => 'test3', 'parent_table' => 'test')); function hsort($array, $parent) { $output = array(); $children = array_filter($array, function ($v) use ($parent) { return $v['parent_table'] === $parent; }); sort($children); $lastchild = NULL; foreach ($children as $child) { if ($child != $lastchild && !is_null($lastchild)) { $output[] = $lastchild; $output = array_merge($output, hsort($array, $lastchild['table'])); } elseif ($lastchild != NULL) { $output[] = $lastchild; } $lastchild = $child; } if (!is_null($lastchild)) { $output[] = $lastchild; $output = array_merge($output, hsort($array, $lastchild['table'])); } return $output; } echo "table | parent_table\n"; foreach (hsort($array, NULL) as $v) { printf("%-8s| %s\n", $v['table'], $v['parent_table'] ?? 'NULL'); }
Output for 7.1.25 - 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.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
table | parent_table test | NULL test | NULL test2 | test test3 | test test5 | test3 test6 | test5 test4 | NULL

preferences:
123.44 ms | 408 KiB | 5 Q