0

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?

acme
  • 14,654
  • 7
  • 75
  • 109

3 Answers3

2

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);
Hasina
  • 745
  • 5
  • 15
1

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);
});
meze
  • 14,975
  • 4
  • 47
  • 52
0

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