2012-06-15 63 views
0

這是Detect future duplicate values while iterating through MySQL results in PHP的後續行動。通過數組計算整體和部門排名

我產生結果的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 
... 

但我堅持就如何遍歷並得到我的兩個相應的等級,如以及爲每個適當地檢測關係。

回答

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>"; 
+0

謝謝,但2個問題:不給我在這兩個部門的整體排名,而關係不正確處理(只有一個捆綁隊有「T- 「附加,並且下一個團隊的等級不適當增加)。 – hannebaumsaway