Sorting an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Garry
Forum Newbie
Posts: 8
Joined: Wed Jun 23, 2004 7:10 am
Location: Surrey, England

Sorting an array

Post by Garry »

I would like to be able to sort an array depending upon the click of a mouse on a column header (got to be standard stuff, I'm guessing!).
However, I'm not familiar with sorting arrays, so within this snippet of code, how do I correct the function sortclubs1 so that it will sort as per the onClick selection? Some of the sorts may be ascending, some descending - I'm happy to have 2 sort functions defined for that purpose if necessary.

Code: Select all

function sortclubs1($order)
{
  sort($foo[$order]);
}


 echo "<h3 align=center>Clubs eligible for Euro Fantasy League</h3><br>";
 /* Start a table, with column headers */
 echo "\n<table border=1 bgcolor=444444 align=center>\n<tr>\n" .
         "\n\t<th><a href="javascript:void(0)" onClick="sortclubs1('clubid')">Club ID</a></th>" .
         "\n\t<th><a href="javascript:void(0)" onClick="sortclubs1('clubname')">Club</a></th>" .
         "\n\t<th>Country</th>" .
         "\n\t<th>Balls</th>" .
         "\n\t<th>Def Pts</th>" ."\n\t<th><a href="javascript:void(0)" onClick="sortclubs1('defpts')">Def Pts</a></th>" .

         "\n\t<th>Mid Pts</th>" .
         "\n\t<th>Att Pts</th>" .
         "\n\t<th>European Competition</th>" .
         "\n</tr>";

foreach($squad as $foo)
{ 
    echo
        '<tr align=center><td>' . 
        $foo['clubid'] .
        '</td><td>' .
        '<a onmouseover="this.style.color=''red''" style="COLOR: yellow; TEXT-DECORATION: none" 

onmouseout="this.style.color=''yellow''" href="club2.php?$clubid">' . 
        $foo['clubname'] .
        '</a></td><td>' .
        $foo['country_name'] . 
        '</td><td>' . 
        $foo['balls'] . 
        '</td><td>' .
        $foo['defpts'] .
        '</td><td>' .
        $foo['midpts'] . 
        '</td><td>' .
        $foo['attpts'] . 
        '</td><td>' .
        $foo['competition'] .
        '</td></tr>'; 
} 

echo          "\n</table>";
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post by kettle_drum »

You can just use a switch with the different sorts in:

Code: Select all

switch($order){
   case 1:
      sort($array);
      break;
   case 2:
      asort($array);
      break;
   case 3:
      arsort($array);
      break;
}
Post Reply