0

Question: how to sort multi dimensional array with object?

Status : I've an array as following.

array(3) {
  [0]=>
  object(Photo_model)#25 (5) {
    ["id"]=>
    int(5)
    ["file_name"]=>
    string(36) "A49361605AE049D687CDC3FEAF7D3236.jpg"
    ["user_id"]=>
    int(1)
    ["challenge_id"]=>
    string(1) "2"
    ["score"]=>
    int(19)
  }
  [1]=>
  object(Photo_model)#28 (5) {
    ["id"]=>
    int(2)
    ["file_name"]=>
    string(36) "A49361605AE049D687CDC3FEAF7D3236.jpg"
    ["user_id"]=>
     int(1)
    ["challenge_id"]=>
    string(1) "2"
    ["score"]=>
    int(10)
  }
  [2]=>
  object(Photo_model)#29 (5) {
      ["id"]=>
      int(3)
      ["file_name"]=>
      string(36) "A49361605AE049D687CDC3FEAF7D3236.jpg"
      ["user_id"]=>
      int(1)
      ["challenge_id"]=>
      string(1) "2"
      ["score"]=>
      int(15)
  }
}

I tried to sort above array by score. I created a function as follow.

aarsort (&$array, 'score');
function aarsort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    arsort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

But it is not working. How can I sort the multidimensional array by key (score)?

result should be by id => 5,3,2

Thu Ra
  • 2,013
  • 12
  • 48
  • 76

3 Answers3

3

Your array is only 1 dimensional, and there is an object in each array item.

After all, to sort a 1D array consisting of objects, and sort by a certain property of the objects, use usort

usort($array, function($a, $b) {
    return $a->score - $b->score
});

To get id => 5, 3, 2 from above, just loop through the array from the above code and access the property to get it

$ids = array();
foreach ($array as $item) {
    $ids[] = $item->id;
}
var_dump($ids);

And I am not sure if the order is right. If it turns out to be reverse order, just negate the result of the closure in the usort function.

luiges90
  • 4,493
  • 2
  • 28
  • 43
0

It just example.

//$newarray for store all array id
//$array is your previous array . You just enter your all index whose key id store in new array 
$newarray = array();
foreach($array as $obj => $id)
{
    $newarray[] = $id[$key];
}

array_multisort($newarray,SORT_ASC,$array);
Syed Osama
  • 133
  • 1
  • 1
  • 8
0

I've done this problem by php.net

// Obtain a list of columns
                foreach ($array as $key => $row) {
                    $_score[$key]  = $row->score;
                }

                // Sort the data with volume descending, edition ascending
                // Add $data as the last parameter, to sort by the common key
                array_multisort($_score, SORT_DESC, $array);
Thu Ra
  • 2,013
  • 12
  • 48
  • 76