Jump to content

Sorting arrays by 2 different values..


Zugzwangle

Recommended Posts

Hi all,

 

I sorted this array:

 

array (
 'team4' => 
 array (
   'brd_points' => 16,
   'ttl_points' => 1,
 ),
 'team1' => 
 array (
   'brd_points' => 14,
   'ttl_points' => 5,
 ),
 'team3' => 
 array (
   'brd_points' => 12,
   'ttl_points' => 3,
 ),
 'team2' => 
 array (
   'brd_points' => 7,
   'ttl_points' => 3,
 ),
 'team5' => 
 array (
   'brd_points' => 7,
   'ttl_points' => 0,
 ),
)

 

Into this array:

array (
 'team1' => 
 array (
   'brd_points' => 14,
   'ttl_points' => 5,
 ),
 'team2' => 
 array (
   'brd_points' => 7,
   'ttl_points' => 3,
 ),
 'team3' => 
 array (
   'brd_points' => 12,
   'ttl_points' => 3,
 ),
 'team4' => 
 array (
   'brd_points' => 16,
   'ttl_points' => 1,
 ),
 'team5' => 
 array (
   'brd_points' => 7,
   'ttl_points' => 0,
 ),
 ),

 

 

By using this code with array_multisort()

 

foreach ($totals as $key => $row) {
  $ttl_points_check[$key]  = $row['ttl_points'];
}

array_multisort( $ttl_points_check, SORT_DESC, $totals);

That works fine, but what if I firstly want to sort by 'ttl_points', and then by 'brd_points'.. In the case above, team3, should be above team 2!!

 

Thanks for reading and replying!

Link to comment
Share on other sites

I prefer usort() to array_multisort()

 

array_multisort() requires you to create new arrays before you even sort the array - creating more overhead. usort() may take a little more lines of code, but it's probably more efficient and it is easier to understand. The function below is written out to be easy to read and could be condensed. Also, the $a and $b within the return lines may need to be swapped to sort in the order you are looking for - I didn't test it.

 

function sortTotals($a, $B)
{
   //Do initial sort on 'ttl_points'
   if($a['ttl_points'] != $b['ttl_points'])
   {
    return $a['ttl_points'] - $b['ttl_points'];
   }
   //Do secondary sort on 'brd_points'
   if($a['brd_points'] != $b['brd_points'])
   {
    return $a['brd_points'] - $b['brd_points'];
   }
   //Both fields are the same values
   return 0;
}

//Usage
usort($totals, "sortTotals");

Link to comment
Share on other sites

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.