how to sort php multidimensional array by other array

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error how to sort php multidimensional array by other array on this date .

I have an array with IDs that looks like

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

and another multidimensional array that looks like

 array(
       0  => array(
                   0 => 4, // order id
                   1 => 23 // item_id
                   2 => 1 // qty
       ),
  1  => array(
                   0 => 9, // order id
                   1 => 66 // item_id
                   2 => 4 // qty
       ),
  2  => array(
                  0 => 8, // order id
                   1 => 17 // item_id
                   2 => 3 // qty
       ),
 )

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.

Answer

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