SplHeap::key()函式用於返回當前元素的鍵(即索引)。
使用方法:
public SplHeap::key ( void ) : mixed
示例:
// 建立一個新的SplMaxHeap物件
$heap = new SplMaxHeap();
// 向堆中插入元素
$heap->insert('apple', 5);
$heap->insert('banana', 3);
$heap->insert('cherry', 8);
$heap->insert('date', 1);
// 獲取堆中當前元素的鍵
while ($heap->valid()) {
echo "Key: " . $heap->key() . "\n";
$heap->next();
}
// 輸出結果:
// Key: 2
// Key: 1
// Key: 0
// Key: 3
在上面的示例中,我們建立了一個SplMaxHeap物件,並向堆中插入了一些元素。然後,我們使用SplHeap::key()函式獲取了堆中當前元素的鍵(索引)。在迴圈中,我們使用SplHeap::valid()函式來檢查堆中是否還有下一個元素,並使用SplHeap::next()函式將指標移動到下一個元素。最後,我們輸出了每個元素的鍵。在這個例子中,鍵的順序是根據元素的優先順序來決定的。