Jump to content

Reverse sort an array of arrays


kreut

Recommended Posts

Hello!

 

Is it possible to reverse sort an array by looking at specific values if the array is multi-dimensional?

 

Array ( 
[0] => Array ( [question_id] => 34 [ratio] => .2 )
[1] => Array ( [question_id] => 45 [ratio] => .7 )
[2] => Array ( [question_id] => 51 [ratio] => 1 )
[3] => Array ( [question_id] => 55 [ratio] => 0.5 )
[4] => Array ( [question_id] => 57 [ratio] => 0 ) )

 

For example, if I wanted to reverse sort by ratio, the new array of arrays should be:

 

Array ( 
[0] => Array ( [question_id] => 51 [ratio] => 1 )
[1] => Array ( [question_id] => 45 [ratio] => .7 )
[2] => Array ( [question_id] => 55 [ratio] => 0.5 )
[3] => Array ( [question_id] => 34 [ratio] => .2 )
[4] => Array ( [question_id] => 57 [ratio] => 0 ) )

 

 

 

Thanks!

 

-Eric

Link to comment
https://forums.phpfreaks.com/topic/242008-reverse-sort-an-array-of-arrays/
Share on other sites

I was just going to post a link to array_multisort(), but (not tested, you get the idea):

 

foreach($array as $key => $val) {
    $ratio[$key] = $val['ratio'];
}
array_multisort($ratio, SORT_DESC, $array);

print_r($array);

I know this isn't what you asked, but if you wanted to sort each array separately you can write it like this

 

$array = Array ( 
[0] => Array ( [question_id] => 51 [ratio] => 1 )
[1] => Array ( [question_id] => 45 [ratio] => .7 )
[2] => Array ( [question_id] => 55 [ratio] => 0.5 )
[3] => Array ( [question_id] => 34 [ratio] => .2 )
[4] => Array ( [question_id] => 57 [ratio] => 0 ) )

array_multisort($array[0],SORT_DESC);
array_multisort($array[1],SORT_DESC,SORT_NUMERIC); //etc.....

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.