可以在php中按多列添加和排序吗?

时间:2019-06-05 16:02:53

标签: php

我想在另一列的基础上添加一列的结果,并按顺序显示结果。

我正在查看是否可以将每个团队的前2个得分加在一起,然后根据哪个得分最高的团队进行排序。

表信息:

team1score   -   1000
team1score   -   1500
team1score   -   1600
team2score   -   1700
team2score   -   1800
team2score   -   1900
team3score   -   1100
team3score   -   1200
team3score   -   1300

任何方向,无论是内置的PHP还是选择字符串排序魔术。我只是不确定目前要走的最佳方向。

我想显示的结果是:

team2score - 37
team1score - 31
team3score - 25

2 个答案:

答案 0 :(得分:0)

没有直接执行此操作的命令,但是您可以编写一个程序轻松执行此操作。我要做的是根据原始数组创建一个包含所有键值的数组,并将分数存储为数组:

// Assume $scores is your original array with team in index 0 and score in index 1
// I will turn it into $a[team] = array(score, score, score...)
$a = array();
foreach($scores as $teamscore) {
  $team = $teamscore[0];
  $score = $teamscore[1];
  if(!isset($a[$team])) $a[$team] = array();
  $a[$team][] = $score;
}

现在,我想将每个分数数组转换为前两个分数的总和。如果我对每一个进行反向排序,那很容易。然后,我可以总结一下索引0和索引1。

foreach($a as $team=>$scores) {
  rsort($scores);
  $a[$team] = $scores[0] + $scores[1];
  // I assumed there are at least 2 scores per team
}

最后,您可以对$ a个保持键关联进行反向排序。

arsort($a);
foreach($a as $team=>$sum) {
  print "$team\t$sum\n";
}

我以非常冗长的方式进行了此操作,希望它很有道理。通过将指令组合在一起来大幅度减少代码行是微不足道的。此外,如果您希望显示的分数是总和除以100,则可以轻松打印$ sum / 100。

答案 1 :(得分:0)

如果该列位于MySQL中(不清楚),则类似以下的查询应按降序返回前3个得分的数组,然后可以循环遍历:

SELECT  team_score, right(trim(team_score), length(trim(team_score)) - locate('-',team_score) -1) + 0 as just_score from table order by just_score DESC LIMIT 3