Jump to content

[SOLVED] multidimensional array sort by more than one element


lxndr

Recommended Posts

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.

 

__

 

 

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.