<?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');
}
preferences:
25.67 ms | 407 KiB | 5 Q