Sort multidimensional array based on another one containing the desired order I have an array like this:
$array = [
    ['id' =&gt; 1, 'content' =&gt; 'value 1'],
    ['id' =&gt; 2, 'content' =&gt; 'value 2'],
    ['id' =&gt; 3, 'content' =&gt; 'value 3'],
];

I have another array containing the actual order of ids in which $array should be sorted :
$order = [3, 1, 2];

Which means, the result should be this:
$sorted = [
    0 =&gt; ['id' =&gt; 3, 'content' =&gt; 'value 3'],
    1 =&gt; ['id' =&gt; 1, 'content' =&gt; 'value 1'],
    2 =&gt; ['id' =&gt; 2, 'content' =&gt; '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 ids and only those are in $order - so no need to test for that.
I think this would be the cleanest solution. Similar to @YourCommonSense answer, but slightly inverted as ordered index is already there - only values missing.

$sorted = array_flip($order);
foreach ($array as $value) {
    $id = $value['id'];
    $sorted[$id] = $value;
}