Search code examples
phparrayssortingmultidimensional-arraycustom-sort

Sort the rows of a 2d array by a column to be ordered by another flat array


I'm trying to sort a multi-dimensional array by another array, but have so far come up short.
array_multisort seems be working only for real sorting.

Suppose I have these 2 arrays:

$order = array(2, 3, 1);

$data = array(
    array('id' => 1, 'title' => 'whatever'),
    array('id' => 2, 'title' => 'whatever'),
    array('id' => 3, 'title' => 'whatever')
);

Now I would like to sort my $data array according to the order in my $order array.
This is what I would like the result to be:

$data = array(
    array('id' => 2, 'title' => 'whatever'),
    array('id' => 3, 'title' => 'whatever')
    array('id' => 1, 'title' => 'whatever'),
);

I can accomplish this easily by running a nested loop, but that would not scale well (my array is pretty big, and the arrays have many more fields).


Solution

  • There is no built-in function for this in PHP and i am unable to think of any custom function, which would do this using usort. But array_map is simple enough, imo, so why not use it instead?

    $sorted = array_map(function($v) use ($data) {
        return $data[$v - 1];
    }, $order);