Jump to content

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.....

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.