PHP multi-key stable sort with nulls last
PHP
<?php
function sort_records(array $rows, array $keys): array
{
$indexed = [];
foreach ($rows as $i => $row) {
$indexed[] = [$i, $row];
}
usort($indexed, function (array $a, array $b) use ($keys): int {
foreach ($keys as $key => $dir) {
$left = $a[1][$key] ?? null;
$right = $b[1][$key] ?? null;
if ($left === $right) continue;
if ($left === null) return 1;
if ($right === null) return -1;
$cmp = is_string($left) && is_string($right) ? strcmp($left, $right) : $left <=> $right;
return $dir === 'desc' ? -$cmp : $cmp;
}
return $a[0] <=> $b[0];
});
return array_column($indexed, 1);
}