0

我一直使用这种方法来完成这种排序,但对我来说看起来不正确

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] 精度限制怎么样?

有人对此有建议吗?

谢谢你 :)


随时改进标题

4

1 回答 1

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,但实现起来应该不难。

于 2013-09-01T14:49:02.410 回答