3v4l.org

run code in 300+ PHP versions simultaneously
<?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.26, 8.1.0 - 8.1.13, 8.2rc1
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:
33.92 ms | 410 KiB | 5 Q