lxndr Posted July 10, 2008 Share Posted July 10, 2008 I've been using the following function to sort a multi-dimensional array by a numeric key: function sort2d ($array, $index, $order='desc', $natsort=FALSE, $case_sensitive=FALSE) { if(is_array($array) && count($array)>0) { foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index]; if(!$natsort) ($order=='asc')? asort($temp) : arsort($temp); else { ($case_sensitive)? natsort($temp) : natcasesort($temp); if($order!='asc') $temp=array_reverse($temp,TRUE); } foreach(array_keys($temp) as $key) (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key]; return $sorted; } return $array; } I'm using it to sort a league table of football teams and sorting on the number of points they have which is item 7 in the array as follows: $league = sort2d($league, 7); This is where the array elements get assigned within a for loop following various calculations: $league[$j] [0] = $team_name; $league[$j] [1] = $played; // played $league[$j] [2] = $won; // win $league[$j] [3] = $drawn; // drawn $league[$j] [4] = $lost; // lost $league[$j] [5] = $score_for; // for $league[$j] [6] = $score_against; // against $league[$j] [7] = $points; // points $league[$j] [8] = $user; $league[$j] [9] = $score_for - $score_against; // goal difference; What I really need to do though is have a secondary sort based on element 9 which is goal difference. In other words I want to sort by points and then if the points are equal by goal difference. I've tried a few times to update the function to do this but have had no success so far. Can anyone help ? Thanks in advance. __ Link to comment https://forums.phpfreaks.com/topic/114020-solved-multidimensional-array-sort-by-more-than-one-element/ Share on other sites More sharing options...
Barand Posted July 10, 2008 Share Posted July 10, 2008 function leaguesort($a, $b) { if (($p = $b[7] - $a[7]) == 0 ) { return $b[9] - $a[9]; } else return $p; } //sort the array usort ($league, 'leaguesort'); Link to comment https://forums.phpfreaks.com/topic/114020-solved-multidimensional-array-sort-by-more-than-one-element/#findComment-586143 Share on other sites More sharing options...
lxndr Posted July 10, 2008 Author Share Posted July 10, 2008 That worked just fine, many thanks for your help, I hadn't realised it could be done so simply. Will know better next time. __ Link to comment https://forums.phpfreaks.com/topic/114020-solved-multidimensional-array-sort-by-more-than-one-element/#findComment-586283 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.