Search code examples
phparrayssortingmultidimensional-arraycustom-sort

Sort a 2d array by values in a column related to a flat priority array


I have an array with IDs that looks like

 $order_ids = array(8,9,10,4,7);

and another multidimensional array that looks like

$multiarray = [
    [4, 23, 1],
    [9, 66, 4],
    [8, 17, 3],
];

I tried

 $keys = array_flip($order_ids);

 usort($multiarray, function($a, $b) use ($keys)
 {
     return $keys[$a] - $keys[$b[0];
 });

The order_ids of the 2nd array correspond to the values in the first array. What I need to do is sort the 2nd array by the order_ids in the order they are in the 1st array.


Solution

  • You could cycle through the records in $arr and store them in the order set by $order_ids - result in $newArr:

    <?php
    $order_ids = array(8,9,10,4,7);
    
    $arr = [
        [4, 23, 1],
        [9, 66, 4],
        [8, 17, 3],
    ];
    
    foreach($order_ids as $id) {
        foreach($arr as $record) {
            if($record[0] == $id) {
                $newArr[] = $record;
                break;
            }
        }
    }
    

    demo