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.

This question already has an answer here:

I'm a little stuck with some array sorting, maybe someone can help me out?

Given these two arrays:

$sortOrder = array(12, 20, 4);

$data = array(
    (object)array(
        'id' => 4,
        'name' => 'Tom' 
    ),
    (object)array(
        'id' => 12,
        'name' => 'Bob' 
    ),
    (object)array(
        'id' => 20,
        'name' => 'Max' 
    ) 
) 

I want to sort $data by the id order specified in $sortOrder.

So after sorting I want $data to be like this:

$data = array(
    (object)array(
        'id' => 12,
        'name' => 'Bob' 
    ),
    (object)array(
        'id' => 20,
        'name' => 'Max' 
    ), 
    (object)array(
        'id' => 4,
        'name' => 'Tom' 
    ),
) 

How would I do that?

share|improve this question

marked as duplicate by meze, Michael Irigoyen, fotanus, Maerlyn, Veger Jun 4 '13 at 12:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers 3

up vote 1 down vote accepted

usort will help you.

usort($data, function ($a, $b) use ($sortOrder) {
   $pos1 = array_search($a->id, $sortOrder);
   $pos2 = array_search($b->id, $sortOrder);

   return ($pos1 === $pos2) ? 0 : ($pos1 < $pos2 ? -1 : 1);
});
share|improve this answer
    
Thanks, this is the most elegant approach. –  acme Jun 4 '13 at 12:02

please try this. it will print as your expected output.

  $sortOrder = array(12, 20, 4);

 $data = array(
    array(
        'id' => 4,
        'name' => 'Tom' 
   ),
  array(
         'id' => 12,
         'name' => 'Bob' 
     ),
     array(
         'id' => 20,
         'name' => 'Max' 
     ) 
 );

 $sortedArray = array();
 foreach($sortOrder as $id) 
 {
     foreach($data as $_data)
     {
         if($_data["id"] == $id)
         {
             $sortedArray[] = $_data;
             break;
         }
     }
 }

 print_r($sortedArray);
share|improve this answer
    
Thanks, it works! –  acme Jun 4 '13 at 12:03
    
your welcome..:) –  Hasina Jun 4 '13 at 12:06

You try use sort and foreach to made it? http://php.net/manual/en/function.sort.php

share|improve this answer

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