Simple use of PHP Data Structure Queue (SplQueue) and priority queue (SplPriorityQueue) Instances
This article mainly introduces simple Use Cases of PHP Data Structure Queue (SplQueue) and priority queue (SplPriorityQueue). For more information, see
The data structure of queue is simpler, just like queuing in our daily life. It features FIFO ).
In php spl, The SplQueue class implements queue operations. Like the stack, it can also inherit the double-stranded table (spldoubly1_list) for easy implementation.
The summary of the SplQueue class is as follows:
SplQueue is easy to use as follows:
The Code is as follows:
$ Queue = new SplQueue ();
/**
* The difference between a queue and a double-stranded table is that the IteratorMode is changed. The stack IteratorMode can only be:
* (1) spldoubly1_list: IT_MODE_FIFO | spldoubly1_list: IT_MODE_KEEP (default value: save data after iteration)
* (2) spldoubly1_list: IT_MODE_FIFO | spldoubly1_list: IT_MODE_DELETE (delete data after iteration)
*/
$ Queue-> setIteratorMode (spldoubly1_list: IT_MODE_FIFO | spldoubly1_list: IT_MODE_DELETE );
// SplQueue: enqueue () is actually the spldoubly1_list: push ()
$ Queue-> enqueue ('A ');
$ Queue-> enqueue ('B ');
$ Queue-> enqueue ('C ');
// SplQueue: dequeue () is actually the spldoubly1_list: 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 (introduced later.
The class Summary of SplPriorityQueue is as follows:
Simple use of SplPriorityQueue:
?
1 2 3 4 5 6 7 8 9 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; // /** * Set the element team-out mode. * SplPriorityQueue: EXTR_DATA only extracts values. * SplPriorityQueue: EXTR_PRIORITY only extracts priority * SplPriorityQueue: EXTR_BOTH extracts the array containing values and priorities. */ $ Pq-> setExtractFlags (SplPriorityQueue: EXTR_DATA ); While ($ pq-> valid ()){ Print_r ($ pq-> current (); // a c B $ Pq-> next (); } |