Zugzwangle Posted February 7, 2013 Share Posted February 7, 2013 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! Quote Link to comment https://forums.phpfreaks.com/topic/274169-sorting-arrays-by-2-different-values/ Share on other sites More sharing options...
Zugzwangle Posted February 7, 2013 Author Share Posted February 7, 2013 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); Quote Link to comment https://forums.phpfreaks.com/topic/274169-sorting-arrays-by-2-different-values/#findComment-1410804 Share on other sites More sharing options...
Psycho Posted February 7, 2013 Share Posted February 7, 2013 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"); Quote Link to comment https://forums.phpfreaks.com/topic/274169-sorting-arrays-by-2-different-values/#findComment-1410813 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.