Reputation: 307
I got this array, comes from database. The order of values is changeable by the users
Array
(
[0] => 14
[1] => 15
[2] => 9
[3] => 13
[4] => 12
...
[n] => n
)
There is another array, which will be extracted to browser:
Array
(
[0] => Array
(
[id] => 1
...
[nr] => 9
...
)
[1] => Array
(
[id] => 2
...
[nr] => 12
...
)
[2] => Array
(
[id] => 3
...
[nr] => 15
...
)
[n] => Array
)
I need to find a way to sort the this second array by nr
(not id
) and the nr
order comes from the first array.
Any ideas?
Upvotes: 1
Views: 97
Reputation: 7485
You can just map your values to keys, and use that map to re-order.
<?php
$order =
[
2,
5,
1
];
$items =
[
['o' => 1],
['o' => 5],
['o' => 2],
];
foreach($items as $k => $v) {
$map[$v['o']] = $k;
}
var_export($map);
foreach($order as $o) {
$k = $map[$o];
$result[$k] = $items[$k];
}
var_export($result);
Output:
array (
1 => 0,
5 => 1,
2 => 2,
)array (
2 =>
array (
'o' => 2,
),
1 =>
array (
'o' => 5,
),
0 =>
array (
'o' => 1,
),
)
Assuming there's a one-one mapping.
Upvotes: 1
Reputation: 24276
You can flip the first array in order to know what's the order of the id's:
$order = array_flip($order);
Then you simply use usort to sort the array based on the earlier flipped array:
usort($array, static function(array $a, array $b) use ($order) {
return $order[$a['nr']] <=> $order[$b['nr']];
});
Upvotes: 2