Your sorting requirements:
- values not found in the sorting array come before values that ARE found.
- then:
- sort found values by their position in the sorting array
- sort values not found in the sorting array normally/ascending
Flipping your order lookup array will permit improved efficiency while processing before key searching is faster than value searching in php.
Code: (Demo)
$array = ['val1', 'val2', 200, 179, 230, 234, 242];
$order = [230, 234, 242, 179, 100];
$keyedOrder = array_flip($order); // for efficiency
usort($array, function($a, $b) use ($keyedOrder) {
return [$keyedOrder[$a] ?? -1, $a]
<=>
[$keyedOrder[$b] ?? -1, $b];
});
var_export($array);
Output:
array (
0 => 'val1',
1 => 'val2',
2 => 200,
3 => 230,
4 => 234,
5 => 242,
6 => 179,
)
$keyedOrder[$variable] ?? -1
effectively means if the value is not found in the lookup, use -1
to position the item before the lowest value in the lookup array (0
). If the value IS found as a key in the lookup, then use the integer value assigned to that key in the lookup.
From PHP7.4, arrow function syntax can be used to make the snippet more concise and avoid the use()
declaration.
usort($array, fn($a, $b) => [$keyedOrder[$a] ?? -1, $a] <=> [$keyedOrder[$b] ?? -1, $b]);
0
solved php – sort an array according to second given array