This article mainly introduces the simple use of PHP Data Structure Queue (SplQueue) and priority queue (SplPriorityQueue) instances. If you need a friend, you can refer to the queue data structure which is simpler, like queuing in our lives, 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:
$ 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/*** sets the element queuing mode * SplPriorityQueue: EXTR_DATA only extracts the value * SplPriorityQueue: EXTR_PRIORITY only extracts the priority * SplPriorityQueue :: EXTR_BOTH extract array containing value and priority */$ pq-> setExtractFlags (SplPriorityQueue: EXTR_DATA); while ($ pq-> valid ()) {print_r ($ pq-> current (); // a c B $ pq-> next ();}