為了讓大家了解 SplHeap 的用途,我寫了一個簡單的範例腳本,用來顯示比利時甲級足球聯賽 (Jupiler League) 球隊的排名。
<?php
/**
* A class that extends SplHeap for showing rankings in the Belgian
* soccer tournament JupilerLeague
*/
class JupilerLeague extends SplHeap
{
/**
* We modify the abstract method compare so we can sort our
* rankings using the values of a given array
*/
public function compare($array1, $array2)
{
$values1 = array_values($array1);
$values2 = array_values($array2);
if ($values1[0] === $values2[0]) return 0;
return $values1[0] < $values2[0] ? -1 : 1;
}
}
// Let's populate our heap here (data of 2009)
$heap = new JupilerLeague();
$heap->insert(array ('AA Gent' => 15));
$heap->insert(array ('Anderlecht' => 20));
$heap->insert(array ('Cercle Brugge' => 11));
$heap->insert(array ('Charleroi' => 12));
$heap->insert(array ('Club Brugge' => 21));
$heap->insert(array ('G. Beerschot' => 15));
$heap->insert(array ('Kortrijk' => 10));
$heap->insert(array ('KV Mechelen' => 18));
$heap->insert(array ('Lokeren' => 10));
$heap->insert(array ('Moeskroen' => 7));
$heap->insert(array ('Racing Genk' => 11));
$heap->insert(array ('Roeselare' => 6));
$heap->insert(array ('Standard' => 20));
$heap->insert(array ('STVV' => 17));
$heap->insert(array ('Westerlo' => 10));
$heap->insert(array ('Zulte Waregem' => 15));
// For displaying the ranking we move up to the first node
$heap->top();
// Then we iterate through each node for displaying the result
while ($heap->valid()) {
list ($team, $score) = each ($heap->current());
echo $team . ': ' . $score . PHP_EOL;
$heap->next();
}
?>
結果輸出如下:
布魯日俱樂部 (Club Brugge): 21
安德列治 (Anderlecht): 20
標準列日 (Standard): 20
梅赫倫 (KV Mechelen): 18
聖圖爾登 (STVV): 17
聚爾特瓦雷赫姆 (Zulte Waregem): 15
根特 (AA Gent): 15
貝爾斯霍特 (G. Beerschot): 15
查勒羅瓦 (Charleroi): 12
亨克 (Racing Genk): 11
瑟蘭聯 (Cercle Brugge): 11
科特賴克 (Kortrijk): 10
洛克倫 (Lokeren): 10
韋斯特洛 (Westerlo): 10
穆斯克龍 (Moeskroen): 7
羅斯勒爾 (Roeselare): 6
希望這個例子能幫助大家更深入地理解和應用 SplHeap。