0

这是在 PHP 中迭代 MySQL 结果时检测未来重复值的后续行动。

我有一个产生结果的 SQL 查询:

team_id   division_id   wins
-------------------------------
10        2             44
9         2             42
5         1             42
2         1             42
3         1             41
11        2             40
1         1             36
8         2             31
7         2             29
12        2             24
4         1             20
6         1             18

我正在尝试计算给定团队的整体分区排名

例如,team_id = 1

Overall:       7
Divisional:    4

对于team_id = 3

Overall:       5
Divisional:    3

对于team_id = 9

Overall:     T-2  //must indicate tie
Divisional:    2

正如您从链接的先前问题/答案中看到的那样,我可以很好地计算总体排名。计算分区排名也存在问题(包括正确处理平局)。

我尝试将结果存储在一个多维数组$arr['wins']['division_id']['team_id']中,例如...

44 =>  2 => 10
42 =>  1 =>  5
             2
       2 =>  9
41 =>  1 =>  3
40 => 11 =>  2
...

但是对于如何迭代并获得我的两个各自的排名,以及为每个.

4

1 回答 1

0

尝试这样的事情:

// Dataset as defined on question
$arr = array(
array('team_id' => 10, 'division_id' => 2, 'wins' => 44),
array('team_id' => 9, 'division_id' => 2, 'wins' => 42),
array('team_id' => 5, 'division_id' => 1, 'wins' => 42),
array('team_id' => 2, 'division_id' => 1, 'wins' => 42),
array('team_id' => 3, 'division_id' => 1, 'wins' => 41),
array('team_id' => 11, 'division_id' => 2, 'wins' => 40),
array('team_id' => 1, 'division_id' => 1, 'wins' => 36),
array('team_id' => 8, 'division_id' => 2, 'wins' => 31),
array('team_id' => 7, 'division_id' => 2, 'wins' => 29),
array('team_id' => 12, 'division_id' => 2, 'wins' => 24),
array('team_id' => 4, 'division_id' => 1, 'wins' => 20),
array('team_id' => 6, 'division_id' => 1, 'wins' => 18));


$divisionTeam = array();
$divisionWins = array();
foreach($arr as $team) {
    $divisionTeam[$team['division_id']][] = $team['team_id'];
    $divisionWins[$team['division_id']][] = $team['wins'];
}



echo "<pre>";
foreach (array_keys($divisionTeam) as $division_id) {
    $rank = 0;
    $prevWins = -1;
    echo "DIVISION $division_id \n";
    foreach ($divisionTeam[$division_id] as $index => $team_id) {

       if ($prevWins == $divisionWins[$division_id][$index]) {
           echo $team_id . " T - " . $rank . "\n";
       }
       else { 
           $rank++;
           echo $team_id . " " . $rank . "\n";
       }
       $prevWins = $divisionWins[$division_id][$index];

    }
}
echo "</pre>";
于 2012-06-15T22:42:33.740 回答