Home >Backend Development >PHP Tutorial >Simple usage examples of PHP data structure queue (SplQueue) and priority queue (SplPriorityQueue)_PHP tutorial
This article mainly introduces PHP data structure queue (SplQueue) and priority queue (SplPriorityQueue) Simple usage examples, friends in need can refer to it
Queue is a simpler data structure, just like queuing in our lives. Its characteristic is first-in-first-out (FIFO).
The SplQueue class in PHP SPL implements queue operations. Like the stack, it can also be easily implemented by inheriting the SplDoublyLinkedList.
The SplQueue class summary is as follows:
SplQueue is simply used as follows:
The code is as follows:
$queue = new SplQueue();
/**
* It can be seen that the difference between queue and double linked list is that the IteratorMode has changed. The IteratorMode of the stack can only be:
* (1)SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP (default value, data is saved after iteration)
* (2)SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE (data deleted after iteration)
*/
$queue->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);
//SplQueue::enqueue() is actually SplDoublyLinkedList::push()
$queue->enqueue('a');
$queue->enqueue('b');
$queue->enqueue('c');
//SplQueue::dequeue() is actually SplDoublyLinkedList::shift()
print_r($queue->dequeue());
foreach($queue as $item) {
echo $item .PHP_EOL;
}
print_r($queue);
The priority queue SplPriorityQueue is implemented based on the heap (described later).
The class summary of SplPriorityQueue is as follows:
SplPriorityQueue is simple to use:
?
10 11
12
13
14
15
16
17
18
19
20
21
|
$pq = new SplPriorityQueue(); $pq->insert('a', 10); $pq->insert('b', 1); $pq->insert('c', 8); echo $pq->count() .PHP_EOL; //3 echo $pq->current() . PHP_EOL; //a /** * Set element dequeue mode * SplPriorityQueue::EXTR_DATA only extracts values * SplPriorityQueue::EXTR_PRIORITY only extracts the priority * SplPriorityQueue::EXTR_BOTH extracts the array containing value and priority */ $pq->setExtractFlags(SplPriorityQueue::EXTR_DATA); while($pq->valid()) { print_r($pq->current()); //a c b $pq->next(); } |