SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2005
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    sort array, change subsequent key sort direction?

    Using PHP & MySql, I have:

    $record[$teamid] = array('wins'=>$wins, 'losses'=>$losses, 'ties'=>$ties);


    Example for TeamA, TeamB, TeamC in array:

    record[0] = [2, 1, 0];
    record[1] = [2, 0, 0];
    record[2] = [3, 0, 0];


    When I print the output using arsort($record), I get:

    TeamC 3-0-0
    TeamA 2-1-0
    TeamB 2-0-0

    because it is sorting from high-to-low starting with the wins, then losses, then ties.

    Since 2-1-0 is a worse win % than 2-0, I want the output to be:

    TeamC 3-0-0
    TeamB 2-0-0
    TeamA 2-1-0


    Is there a way to specify that 'losses' be sorted from low-to-high?

    Thank you for your time.

  2. #2
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Shamelessly poached from manual page on multisort

    PHP Code:

    // renamed keys so that success should show TeamA, B, C in correct order

    $record['TeamC'] = array(210); // bottom team, they had a loss
    $record['TeamB'] = array(200);
    $record['TeamA'] = array(300);  // top team

    // Obtain a list of columns
    foreach ($record as $key => $row) {
        
    $wins[$key]  = $row[0];
        
    $losses[$key] = $row[1];
    }

    // Sort the data with volume descending, edition ascending
    // Add $data as the last parameter, to sort by the common key

    array_multisort($winsSORT_DESC$lossesSORT_ASC$record);

    var_dump($record);

    // gives, TeamA, B, C:

    array
      
    'TeamA' => 
        array
          
    => int 3
          1 
    => int 0
          2 
    => int 0
      
    'TeamB' => 
        array
          
    => int 2
          1 
    => int 0
          2 
    => int 0
      
    'TeamC' => 
        array
          
    => int 2
          1 
    => int 1
          2 
    => int 0 

  3. #3
    SitePoint Enthusiast
    Join Date
    Apr 2005
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you...will give it a shot!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •