Search code examples
phplaravellaravel-collection

Sorting collection 2 times


So I want to sort a collection (that's ok for me) but if in this sort result 2 values are equal, I want to compare two other values to determine what goes first.

Ex: I have 30 teams, they all have points, but some teams can have the same number of points. If so, I want to check the victories each team has and put the team with most victories in front of the one with the less.

rankings = $team_stats->sortByDesc(function($product) { return ($product['nhl_season_w'] * 2) + $product['nhl_season_otl'] });

So yeah! That sorts the team's points, now I want to sort the equalities by victories.

Thanks for the help!

EDIT SOLVED:

I use $key + 1 to make sure my team ID's stays the same so it's easier to use to get anything else from the team ranking :)

enter image description here


Solution

  • Create a multi dimension array, with points being the the first key and victory being the second key, php will automatically sort them key wise.

    <?php 
    //each array with (Teams, Points, Wins)
    $rank[] = array('Team' => "A", 'Points' => 24, 'Wins' => 11);
    $rank[] = array('Team' => "B", 'Points' => 26, 'Wins' => 11);
    $rank[] = array('Team' => "C", 'Points' => 25, 'Wins' => 10);
    $rank[] = array('Team' => "D", 'Points' => 24, 'Wins' => 12);
    $rank[] = array('Team' => "E", 'Points' => 25, 'Wins' => 11);
    $rank[] = array('Team' => "F", 'Points' => 27, 'Wins' => 13);
    
    foreach ($rank as $key => $row) {
        $points[$key]  = $row['Points'];
        $wins[$key] = $row['Wins'];
    }
    
    array_multisort($points, SORT_DESC, $wins, SORT_DESC, $rank);
    
    echo "<ol>";
    for ($line = 0; $line < 6; $line++){
        echo "<li><b> Rank</b>";
        foreach($rank[$line] as $key => $value){
            echo "|".$key."-".$value."|";
        }
        echo "</li>";
    }    
    echo "</ol>";
    ?>