Search code examples
phparrayssortingmultidimensional-array

Sort a 2d array by another flat array of priority values


I have an array with IDs that looks like

array(
      0  => 12
      1  => 30
      2  => 50
      3  => 11
      4  => 22
      5  => 45
      [...]
)

and another multidimensional array that looks like

array(
      0  => array(
                  'id' => 12,
                  'title' => 'title 12',
      ),
      1  => array(
                  'id' => 50,
                  'title' => 'title 50',
      ),
      2  => array(
                  'id' => 11,
                  'title' => 'title 11',
      ),
      3  => array(
                  'id' => 30,
                  'title' => 'title 30',
      ),
      4  => array(
                  'id' => 45,
                  'title' => 'title 45',
      ),
      5  => array(
                  'id' => 22,
                  'title' => 'title 22',
      ),

)

The 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 IDs of the sub-arrays in the order they are in the 1st array.


Solution

  • Assuming the array with the IDs is named $order and the array with the values is named $items:

    $keys = array_flip($order);
    
    usort($items, function($a, $b) use($keys)
    {
        return $keys[$a['id']] - $keys[$b['id']];
    });