我一直用这种方法来完成这种排序, 但对我来说看起来不正确
usort($array, function($team1, $team2){
$t1 = ($team1->points * 1000) + ($team1->goalsFor - $team1->goalsAgainst);
$t2 = ($team2->points * 1000) + ($team2->goalsFor - $team2->goalsAgainst);
if($t1 == $t2) return 0;
return $t1 > $t2 ? 1 : -1;
});
此方法的替代方法是使用str_pad,它几乎完全相同
基本上我所做的是用零分隔分类主题
$t1 = 32008; // 32 points with a GD of 8
$t2 = 32003; // 32 points with a GD of 3
但是如果球队有一个奇怪的目标差异怎么办?
$t1 = 32008; // 32 points with a GD of 8
$t2 = 33000; // 32 points with a GD of 1000
显然这不可能发生,但这是一个例子
这是一个好方法吗? 32-64位/浮点数[im]精度限制怎么样?
有人对此有建议吗?
谢谢你:)随时改进标题
答案 0 :(得分:1)
更好的方法是:
function ($team1, $team2) {
if ($team1->points != $team2->points) {
return $team1->points > $team2->points ? 1 : -1;
}
$diff1 = $team1->goalsFor - $team1->goalsAgainst;
$diff2 = $team2->goalsFor - $team2->goalsAgainst;
if ($diff1 != $diff2) {
return $diff1 > $diff2 ? 1 : -1;
}
return 0;
}
或者,在Java中(使用Guava),我会这样写:
public int compare(Team team1, Team team2) {
return ComparisonChain.start()
.compare(team1.getPoints(), team2.getPoints)
.compare(team1.getGoalsFor() - team1.getGoalsAgainst(),
team2.getGoalsFor() - team2.getGoalsAgainst())
.result();
}
显然,PHP没有ComparisonChain
,但它应该不难实现。