The recent BI project has been rebuilt, the original data is through the PHP loop analysis of data, change, want to use an iterator. Here I will summarize the PHP iterator
Iterators are sometimes called cursors (cursor) software design patterns that can be visited on container objects (container, such as a list or vector), and designers do not need to care about the contents of a container object. Just like the cursor principle in SQL, traverse Access.
PHP language is different from other languages, such as Java, Python and other languages will iterator perfect integration, we call the implicit iterator (implicit iterator). PHP5 started to support the interface, so the iterator interface was built in at this time. So in PHP total, you define a class, and implement the iterator interface, then your class object is Zend_iter_object, otherwise it is zend_iter_plain_object.
For a Zend_iter_plain_object class, foreach obtains the object's default property array by Hash_of, and then foreach the array.
For Zend_iter_object class objects, a foreach is done by calling the iterator interface-related functions implemented by the object.
Look at the following example, our actual code to illustrate:
<?php
/**
* Iterator mode of simple implementation *
*
class Mysample impplements iterator {
private $_items;
Public function __construct (& $data) {//Use reference
$this->_items = $data;
}
Gets the public
function present () {return current (
$this->_items)
that points to now; Point to next public
function next () {
next ($this->_items);
}
Gets the key public
function key () {return
key ($this->_items) that
is currently pointing to;
Resets public
function rewind () {
reset ($this->_items);
Whether valid data exists, whether there is a legitimate public
function valid () {return
($this->_current ()!= FALSE);
}
Test
$data = Array (1, 2, 3, 4, 5);
$sa = new Mysample ($data);
foreach ($sa as $k => $v) {
echo $key, ', $v, ' <br/> ';
}
? >
Different iterators have different interfaces, in PHP: Next (moves to the next element), Corrent () (returns the current element), valid () (checks the end of the iteration), Rewind () (restarts from the beginning), key (returns the index of the current element). Of course you can write your own iterator, or you can use the iterator in the system.
While loops are most commonly used in PHP
<?php
//As above while
($iterator->valid ()) {
$element = $iterator->current ();//get current element $ Iterator->next ();
>
The above code is not very simple and convenient.
Using iterators to analyze data is important, with two main reasons
1, the use of PHP iterator can use object-oriented implementation of common data structure, such as: list, stack, queue and so on. Most data structures can be implemented
2, easy to use, flexible, prevent the death cycle and other illogical points.