排序集合2次

时间:2017-06-07 14:11:31

标签: php laravel laravel-collection

所以我想对一个集合进行排序(这对我来说没问题)但是如果在这种结果中2个值相等,我想比较另外两个值来确定最先出现的是什么。

Ex:我有30支球队,他们都有积分,但有些球队可以获得相同数量的积分。如果是这样的话,我想检查每支球队的胜利,并让球队在最少的球队面前获得最多的胜利。

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

所以是的!这样可以对球队的分数进行排序,现在我想通过胜利对这些平等进行排序。

感谢您的帮助!

编辑已解决:

我使用$ key + 1确保我的团队ID保持不变,因此从团队排名中获取其他任何内容都更容易:)

enter image description here

2 个答案:

答案 0 :(得分:2)

只需在点值

之后连接胜利
$rankings = $team_stats->sortByDesc(function($product) {
     return (($product['nhl_season_w'] * 2) + $product['nhl_season_otl']) . '_' . $procuct['victories'];
});

这会将胜利添加到排序字符串中,并确保当两个产品具有相同分数时,最高胜利保持在最高位置。

答案 1 :(得分:1)

创建一个多维数组,其中点是第一个键,胜利是第二个键,php将自动按键排序。

<?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>";
?>