SPL is the abbreviation for standard PHP library (PHP).
SPL provides multiple iterator classes that provide iterative access, filtering data, caching results, and controlling paging. , because PHP is always growing, I try to list all of the iteration classes in SPL. Some of the following iterator classes are required php5.4, and others such as the Searhiteratoer class have been removed in the latest PHP version
1.ArrayIteratoer
Creating an iterator from a PHP array eliminates the work of a method that directly implements the iterator interface when it is used with the Iteratoraggregate class.
<示例>
$b = Array ( ' name ' = ' Mengzhi ', ' age ' = ' + ' , ' city ' = ' Shanghai '); $a = new Arrayiterator ($b); $a- >append ( ' home ' = ' China ', ' work ' = ' developer ' ); $c = $a->getarraycopy (); Print_r ($ a); Print_r ($c); /**outputarrayiterator Object ( [storage:ArrayIterator:private] = = Array ( [name] = Mengzhi [Age] = [City ] = Shanghai [0] = = Array ( [Home] = [Work ] + = Developer)) Array ( [name] + Mengzhi [age] = [City ] = Shanghai [ 0] = = Array ( [Home] = China [Work] = Developer
2. Limititerator
Returns the starting index point for the given number of results and the results taken from the collection:
<示例>
Create an iterator to is limited $fruits = new Arrayiterator ( ' Apple ', ' banana ', ' cherry ', ' Damson ', ' elderberry ' )); Loop over first three fruits only foreach (New Limititerator ($fruits, 0, 3) as$fruit) { var_dump ($fruit);} echo "\ n "; Loop from third fruit until the end//Note:offset starts from zero for Apple foreach (New Limititerator ($fruits, 2) a S$fruit) { print_r ($fruit);}
3. Appenditerator
Iterate through several different iterators sequentially. For example, you want to iterate over two or more combinations in a single loop. The Append method of this iterator is similar to the Array_merge () function to merge the array.
$array _a = new Arrayiterator (Array (' A ', ' B ', ' C ')); $array _b = new Arrayiterator (Array (' d ', ' e ', ' f ')); $iterator = new Appenditerator; $iterator->append ($array _a); $iterator->append ($array _b); foreach ($iteratoras $current) {
4. Filteriterator
Based on the Outeriterator interface, it is used to filter the data and return elements that meet the criteria. You must implement an abstract method, accept (), which must return TRUE or FALSE for the current item of the iterator
Class Userfilter extends Filteriterator { private$userfilter; Publicfunction __construct (Iterator $iterator, $filter) { parent::__construct ($iterator); $this->userfilter = $filter; } Publicfunction Accept () { $user = $this->getinneriterator ()->current (); if (strcasecmp ($user [' name '], $this->userfilter) = = 0) { return false; } return true; } } $array = Array ( ' name ' = ' Jonathan ', ' id ' = ' 5 ' ), Array ( ' Name ' = ' Abdul ', ' id ' = ' + '), $object = new Arrayobject ($array);//Remove the person named Abdul $iterator = n EW Userfilter ($object->getiterator (), ' Abdul '); foreach ($iteratoras $result) { echo$result[' name '];}
5. Regexiterator
Inherits Filteriterator, which supports the use of regular expression patterns to match and modify elements in iterators. is often used to match strings.
$a = new Arrayiterator (Array (' test1 ', ' test2 ', ' test3 ')); $i = new Regexiterator ($a, '/^ (test) (\d+)/', regexiterator::replace); $i->replacement = ' $2:$1 '; Print_r (Iterator_to_array ($i)); /**outputarray ( [0] = 1:test [1] = 2:test
6. Iteratoriterator
A common type of iterator, and all classes that implement the Traversable interface can be accessed iteratively.
7. Cachingiterator
Used to perform an iterative operation that reads an element in advance, for example to determine whether the current element is the last element.
$array = Array (' Koala ', ' kangaroo ', ' wombat ', ' wallaby ', ' emu ', ' kiwi ', ' Kookaburra ', ' platypus '); try { $object = new Cachingiterator (new Arrayiterator ($array)); foreach ($objectas $value) { echo$value; if ($object->hasnext ()) { echo ', '; }} } catch (Exception $e) {
8. Seekableiterator
An iterator used to create a non-sequential access that allows you to jump to any point in the iterator.
9. Norewinditerator
Used for collections that cannot be iterated multiple times, and is suitable for performing a one-time operation during an iteration.
$fruit = Array (' Apple ', ' banana ', ' cranberry '); $arr = new Arrayobject ($fruit); $it = new Norewinditerator ($arr->getiterator ()); echo "Fruit a:\n"; foreach ($itas $item) { echo$item. "\ n"; } echo "Fruit b:\n"; foreach ($itas $item) {
Ten. Emptyiterator
A placeholder in the form of an iterator that performs no action. You can use this iterator when you want to implement a method of an abstract class and this method needs to return an iterator.
Infiniteiterator.
For continuous access to the data, when iterating to the last element, the iteration is accessed again from the first element.
$arrayit = new Arrayiterator (Array (' Cat ', ' dog '); $infinite = new Infiniteiterator ($ARRAYIT); $limit = new Limititerator ($infinite, 0, 7); foreach ($limitas $value) {
Recursivearrayiterator.
Creates an iterator for the recursive array structure, similar to a multidimensional array. It provides the required operations for many more complex iterators, such as Recursivetreeiterator and Recursiveiteratoriterator iterators.
$fruits = Array ("a" = "lemon", "B" and "Orange", Array ("A" and "Apple", "p" = "pear")); $iterator = new Recursivearrayiterator ($fruits); while ($iterator->valid ()) { //check if a child node is included if ($iterator->haschildren ()) { //output so byte point foreach ($ Iterator->getchildren () As$key = $value) { echo$key. ' : ' . $value. "\ n"; } } else { echo "No children.\n"; } $iterator->next (); }
Recursiveiteratoriterator.
Expands a tree-structured iterator into a one-dimensional structure.
$fruits = Array ("a" = "lemon", "B" and "Orange", Array ("A" and "Apple", "p" = "pear")); $arrayiter = new Recursivearrayiterator ($fruits); $iteriter = new Recursiveiteratoriterator ($arrayiter); foreach ($iteriteras $key = $value) { $d = $iteriter->getdepth (); echo "depth= $d k= $key v= $value \ n"; }
Recursivetreeiterator.
Displays a tree structure in a visual manner.
$hey = Array ("a" = "lemon", "B" and "Orange", Array ("A" and "Apple", "p" = "pear")); $awesome = new Recursivetreeiterator ( new Recursivearrayiterator ($hey), null, NULL, RECURSIVEITERATORITERATOR::LEAVES_ONLY); foreach ($awesomeas $line) echo$line. Php_eol; /**output|-lemon|-orange |-apple
Parentiterator.
is an extended filteriterator iterator that filters out non-parent elements from the Recursiveiterator iterator and finds only the key values of the child nodes. In layman's terms, it is to leave leaves.
$hey = Array ("a" = "lemon", "B" and "Orange", Array ("A" and "Apple", "p" = "pear")); $arrayIterator = new Recursivearrayiterator ($hey); $it = new Parentiterator ($arrayIterator); Print_r (Iterator_to_array ($it)); /**outputarray ( [0] = = Array ([a] + = Apple [p] = Pear
Recursivefilteriterator.
is the recursive form of the Filteriterator iterator and requires the implementation of the abstract accept () method, but in this method you should use the $this->getinneriterator () method to access the iterator that is currently being iterated.
Class Testsonlyfilter extends Recursivefilteriterator { publicfunction accept () { //Find the element containing "leaf" Return$this->haschildren () | | (Mb_strpos ($this->current (), "leaf")!== FALSE); } } $array = Array ("Leaf 1", Array ("Li 2", "Leaf 3", "Leaf 4"), "leaf 5"), $iterator = new Recursivearrayiterator ($array); $filter = new T Estsonlyfilter ($iterator); $filter = new Recursiveiteratoriterator ($filter); Print_r (Iterator_to_array ($filter)); /**outputarray ( [0]/= leaves 1 [1] = 3
Recursiveregexiterator.
is a recursive form of the Regexiterator iterator that accepts only the Recursiveiterator iterator as an iterative object.
$rArrayIterator = new Recursivearrayiterator (Array (' leaf 1 ', array (' Tet3 ', ' leaf 4 ', ' leaf 5 ')); $rRegexIterator = new Recursiveregexiterator ($rArrayIterator, '/^ leaf/', recursiveregexiterator::all_matches); foreach ($rRegexIteratoras $key1 = $value 1) { if ($rRegexIterator->haschildren ()) { //Print all children echo "Children:"; foreach ($rRegexIterator->getchildren () As$key = $value) { echo$value. " "; } echo "\ n"; } else { echo "No children\n";
Recursivecachingiterator.
Executes a recursive operation that reads an element in advance on a recursiveiterator iterator.
Callbackfilteriterator (PHP5.4)
Both the filter and callback operations are performed, and the callback function is called after a matching element is found.
$hey = Array ("Li 1", "Leaf 2", "Leaf 3", "Leaf 4", "Leaf 5", "leaf 6",); $arrayIterator = new Recursivearrayiterator ($hey); function Isye ($current) { return Mb_strpos ($current, ' leaf ')!== false;} $rs = new Callbackfilteriterator ($arrayIterator, ' Isye '); Print_r (Iterator_to_array ($rs)); /**outputarray ( [0] = leaf 2 [1] = leaf 3 [2] = leaf 4 [3] = leaf 5
Directoryiterator.
Directory file Walker
Directoryiterator::getsize
Get File size
Directoryiterator::gettype
Get file type
Directoryiterator::isdir
Returns true if the current item is a directory
Directoryiterator::isdot
Returns true if the current item is. OR:
Directoryiterator::isexecutable
Returns true if the file is executable
Directoryiterator::isfile
Returns true if the file is a regular file
Directoryiterator::islink
Returns true if the file is a symbolic link
Directoryiterator::isreadable
Returns true if the file is readable
Directoryiterator::iswritable
Returns true if the file is writable
Directoryiterator::key
Returns the current directory entry
Directoryiterator::next
Move to the next item
Directoryiterator::rewind
Return the directory pointer to the start position
Directoryiterator::valid
Check if the directory contains more items
$it = new Directoryiterator (".. /"); foreach ($itas $file) { //Use the Isdot () method to filter out "." Separately. and ".." Directory if (! $it->isdot ()) { echo$file. "\ n";
Recursivedirectoryiterator.
Recursive directory file Walker allows you to list all directory hierarchies instead of just one directory.
Recursivedirectoryiterator::getchildren
If this is a directory, returns an iterator for the current item
Recursivedirectoryiterator::haschildren
Returns whether the current item is a directory instead of. Or.
Recursivedirectoryiterator::key
Returns the path and file name of the current directory entry
Recursivedirectoryiterator::next
Move to the next item
Recursivedirectoryiterator::rewind
Return the directory pointer to the start position
Recursiveiteratoriterator::current
Accessing the current element value
Recursiveiteratoriterator::getdepth
Get the current depth of the recursive iteration
Recursiveiteratoriterator::getsubiterator
Get the current active sub-iterator
Recursiveiteratoriterator::key
Access the current key
Recursiveiteratoriterator::next
Move forward to the next element
Recursiveiteratoriterator::rewind
Returns an iterator to the first element of a top-level inner iterator
Recursiveiteratoriterator::valid
Check if the current location is legal
Lists all files in the specified directory $path = Realpath ('. /'); $objects = new Recursiveiteratoriterator (new Recursivedirectoryiterator ($path), recursiveiteratoriterator::self_ First); foreach ($objectsas $name = $object) {
Filesystemiterator.
It's a directoryiterator walker.
$it = new Filesystemiterator ('.. /'); foreach ($itas $fileinfo) {
Globiterator.
File Walker with matching pattern
Find.. /directory. php extension file $iterator = new Globiterator ('./*.php '); if (! $iterator->count ()) { echo ' no php file ';} else { $n = 0; printf ("Total%d php files \ r \ n", $iterator->count ()); foreach ($iteratoras $item) { printf ("[%d]%s\r\n", + + $n, $iterator->key ());
Multipleiterator.
Connectors for iterators, see example
$person _id = new Arrayiterator (Array (' 001 ', ' 002 ', ' 003 ')); $person _name = new Arrayiterator (Array (' Zhang San ', ' John Doe ', ' Harry ')); $person _age = new Arrayiterator (Array (22, 23, 11)); $mit = new Multipleiterator (MULTIPLEITERATOR::MIT_KEYS_ASSOC); $mit->attachiterator ($person _id, "id"); $mit->attachiterator ($person _name, "name"); $mit->attachiterator ($person _age, "age"); echo "Number of connected iterators:". $mit->countiterators (). " \ n "; 3 foreach ($mitas $person) { print_r ($person);}/**outputarray ( [ID] = 001 [NAME] + Zhang San [age] = >) array ([id] = 002 [name] + John Doe [age] = +) Array ( [id] = 003 [name] = Harry
Recursivecallbackfilteriterator (PHP5.4)
Recursive operations are performed on the Recursiveiterator iterator while filtering and callback operations are executed, and the callback function is called after a matching element is found.
function Doesntstartwithlettert ($current) { $rs = $current->getfilename (); Return$rs[0]!== ' T '; } $rdi = new Recursivedirectoryiterator (__dir__), $files = new Recursivecallbackfilteriterator ($rdi, ' Doesntstartwithlettert '); foreach (New Recursiveiteratoriterator ($files) as$file) {
Simplexmliterator.
An XML document access iterator that implements access to all nodes in the XML
$xml = <<
PHP BasicsJim Smith
XML Basics
XML; SimpleXML conversion to Array function Sxitoarray ($sxi) {$a = array (); For ($sxi->rewind (); $sxi->valid (); $sxi->next ()) {if (!array_key_exists ($sxi->key (), $a)) { $a [$sxi->key ()] = array (); if ($sxi->haschildren ()) {$a [$sxi->key ()] [] = Sxitoarray ($sxi->current ()); } else {$a [$sxi->key ()] [] = Strval ($sxi->current ()); }} return$a; } $xmlIterator = new Simplexmliterator ($xml); $rs = Sxitoarray ($xmlIterator); Print_r ($RS); /**outputarray ([Book] = Array ([0] = = Array ([title] => ; Array ([0] = PHP Basics) [author] = = Array ([0] = Jim Smith) ) [1] = (XML basics)) **/