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
https://forums.phpfreaks.com/topic/274169-sorting-arrays-by-2-different-values/
Share on other sites

Figured it out!! (Missed 2x parameters).

 

 

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

array_multisort( $ttl_points_check, SORT_DESC, $brd_points_check, SORT_DESC, $totals);

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");

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.