<?php
$orderList = [
'Jake',
'Scully' => [
'pet',
'friend' => [
'Michael',
'Merissa',
],
'Norm',
],
'Amy',
'Charles',
'Hitchcock',
];
$items = [
[ 'name' => 'Scully' ],
[ 'name' => 'Rosa' ],
[ 'name' => 'Bill' ],
[ 'name' => 'Jake' ],
[ 'name' => 'Hitchcock' ],
[ 'name' => 'Amy' ],
];
function getTopLevelItemsFromMixedList(array $mixedList): array {
$topLevels = [];
foreach ($mixedList as $item => $value) {
$topLevels[] = is_int($item) ? $value : $item;
}
return $topLevels;
}
function sort_by(array $array, callable $sortKeyResolver, ...$sortArgs) {
$mapped = array_map($sortKeyResolver, $array);
asort($mapped, ...$sortArgs);
$sorted = [];
foreach ($mapped as $key => $index) {
$sorted[] = $array[$key];
}
return $sorted;
}
$topLevelOrder = getTopLevelItemsFromMixedList($orderList);
$sortKeyResolver = function ($item) use ($topLevelOrder) {
$orderListIndex = array_search($item['name'], $topLevelOrder);
return $orderListIndex === false ? count($topLevelOrder).$item['name'] : $orderListIndex;
};
print_r(sort_by($items, $sortKeyResolver, SORT_NATURAL));
- Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.26, 8.3.0 - 8.3.15, 8.4.1 - 8.4.2
- Array
(
[0] => Array
(
[name] => Jake
)
[1] => Array
(
[name] => Scully
)
[2] => Array
(
[name] => Amy
)
[3] => Array
(
[name] => Hitchcock
)
[4] => Array
(
[name] => Bill
)
[5] => Array
(
[name] => Rosa
)
)
preferences:
91.18 ms | 407 KiB | 5 Q