<?php
$array = [
'note' => [],
'year' => ['2011','2010', '2012'],
'type' => ['conference', 'journal', 'conference'],
];
function array_multisort_custom(array &$array, $columnKey, array $order)
{
// guard clause/condition
if (!array_key_exists($columnKey, $array)) {
throw new Exception('Nominated sorting column not found');
}
// pad rows to consistent size
$maxCount = max(array_map('count', $array));
array_walk($array, fn(&$row) => $row = array_pad($row, $maxCount, null));
// populate first sorting parameter with custom order array
$priority = array_flip($order);
$default = count($order);
foreach ($array[$columnKey] as $v) {
$params[0][] = $priority[$v] ?? $default;
}
// assign reference variables to parameter array for all rows
foreach ($array as &$row) {
$params[] = &$row;
}
array_multisort(...$params);
}
array_multisort_custom($array, 'type', ['conference', 'journal']);
var_export($array);
- Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
- array (
'note' =>
array (
0 => NULL,
1 => NULL,
2 => NULL,
),
'year' =>
array (
0 => '2011',
1 => '2012',
2 => '2010',
),
'type' =>
array (
0 => 'conference',
1 => 'conference',
2 => 'journal',
),
)
preferences:
70.64 ms | 403 KiB | 91 Q