Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

What's the best way to do it?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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']];
});
share|improve this answer
    
im not able to use anonymous functions with my current version of php - how would this work without using them? –  Gaz_Edge Nov 27 '12 at 17:18
    
have opened a question here stackoverflow.com/questions/13589707/… –  Gaz_Edge Nov 27 '12 at 17:39
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.