I have an array like this:
$array = [
['id' => 1, 'content' => 'value 1'],
['id' => 2, 'content' => 'value 2'],
['id' => 3, 'content' => 'value 3'],
];
I have another array containing the actual order of id
s in which $array
should be sorted :
$order = [3, 1, 2];
Which means, the result should be this:
$sorted = [
0 => ['id' => 3, 'content' => 'value 3'],
1 => ['id' => 1, 'content' => 'value 1'],
2 => ['id' => 2, 'content' => 'value 2'],
];
The final requirement is, that the array should be printed using foreach
:
foreach($sorted as $value) {
print $value['content'];
}
I came up with this solution:
function orderArray(array $array, array $order) {
$sorted = [];
foreach($array as $value) {
$id = $value['id'];
$index = array_search($id, $order);
$sorted[$index] = $value;
}
ksort($sorted);
return $sorted;
}
This works fine. However, I wonder whether this is efficent, especially as I have to call ksort
to make the array be printed correctly by foreach
.
Can this be optimized? Maybe there's also a more elegant solution to the problem.
It's a given, that all id
s and only those are in $order
- so no need to test for that.
$array
always correspond to the numbers in the$order
array? \$\endgroup\$$order
contains allid
s from$array
and no other elements. I tried to say that in the footnote - hopefully it's clearer now. \$\endgroup\$$array
, theid
s are in order. Is this always the case? Or is the input array not ordered? \$\endgroup\$1
ton
in$array
. \$\endgroup\$