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, others such as the Searhiteratoer class have been removed in the latest PHP version 1.ArrayIteratoer from the PHP array to create an iterator that, when used with the Iteratoraggregate class, eliminates the direct implementation of ITE The Rator interface method works.
<示例>
$b = Array (' name ' = ' Mengzhi ', ' age ' = ' + ', ' city ' = ' Shanghai '); $a = new Arrayiterator ($b); $a->append (' home ' = ' China ' and ' work ' = ' Developer ' )); $c = $a->getarraycopy (); Print_r ($a); Print_r ($c); /**output arrayiterator Object ([storage:ArrayIterator:private]/= Array ([name] = Men Gzhi [age] = [CITY] = Shanghai [0] = = Array ([ho Me] = [work] = developer)) Array ( [Name] = Mengzhi [age] = [CITY] = Shanghai [0] = = Array ([home] = [Work] = developer) **/2. Limititerator returns the result of the given number of results and the starting index point from which the result was taken out of the collection:
<示例>
Create an iterator to is limited $fruits = new Arrayiterator (' app Le ', ' 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 ($frui TS, 2) as$fruit) {print_r ($fruit); }/**output String (5) "Apple" string (6) "Banana" string (6) "Cherry" Cherrydamsonelderberry */3. Appenditerator iterates 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) {echo$current. " \ n "; }/**output a b c d E F */4. The Filteriterator is based on the Outeriterator interface, which filters the data and returns elements that match the criteria. You must implement an abstract method, accept (), which must return TRUE or FALSE for the current item of the iterator 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 ' = ' 22 '); $object = new Arrayobject ($array); Remove the person named Abdul $iterator = new Userfilter ($object->getiterator (), ' Abdul '); foreach ($iteratoras $result) {echo$result[' name ']; }/**output Jonathan **/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)); /**output Array ([0] = 1:test [1] = 2:test [2] = 3:test) **/6. Iteratoriterator is a common type of iterator, and all classes that implement the Traversable interface can be accessed iteratively. 7. Cachingiterator is 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) {echo$e->getmessage (); }/**output Koala,kangaroo,wombat,wallaby,emu,kiwi,kookaburra,platypus **/8. Seekableiterator is used to create a non-sequential access iterator that allows jumps to any point in the iterator. $array = Array ("Apple", "banana", "cherry", "Damson", "elderberry"); $iterator = new Arrayiterator ($array); $iterator->seek (3); Echo$iterator->current (); /**output damson **/9. Norewinditerator is 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) {Echo$item. "\ n"; }/**output Fruit a:apple banana Cranberry Fruit B: **/10. EmptYiterator an iterator in the form of a placeholder, without performing any 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. One. Infiniteiterator is used for continuous access to data, and 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) {echo "$value \ n"; }/**output cat dog cat dog cat dog cat **/12. Recursivearrayiterator creates an iterator for the recursive array structure, Similar to multidimensional arrays. 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 (); }/**output No Children. No children. A:apple p:pear **/13. 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"; } /**output depth=0 k=a v=lemon depth=0 k=b v=orange depth=1 k=a v=apple depth=1 k=p v=pear **/ 1 4. 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, Recursiveiteratoritera TOR::LEAVES_ONLY); foreach ($awesomeas $line) echo$line. Php_eol; /**output |-lemon |-orange |-apple \-pear **/15. 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)); /**output Array ([0] = = Array ([a] + = Apple [p] = pear) ) **/16. Recursivefilteriterator is the recursive form of the Filteriterator iterator and requires the implementation of the abstract accept () method, but should be used in this method $this->getinneriterator () method to access the iterator that is currently being iterated. Class Testsonlyfilter extends Recursivefilteriterator {publicfunction accept () {//Find out containing " Leaf "element 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 Testsonlyfilter ($iterator); $filter = new Recursiveiteratoriterator ($filter); Print_r (Iterator_to_array ($filter)); /**output Array ([0] = leaf 1 [1] = leaf 3 [2] = leaf 5) **/17. Recursiveregexiterator is a recursive form of a regexiterator iterator that accepts only recursiveiterator iterators 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"; }}/**output No children children: leaves 4 leaves5 **/18. Recursivecachingiterator performs a recursive operation that reads an element in advance on the Recursiveiterator iterator. Callbackfilteriterator (PHP5.4) performs both filtering and callback operations, and a 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)); /**output Array ([0] = leaves 2 [1] = leaves 3 [2] = leaves 4 [3] = leaf 5 [4] = leaf 6) **/20. Directoryiterator Directory File Walker method description directoryiterator::getsize Get file size directoryiterator::gettype get file type Directoryiterator: : Isdir If the current item is a directory, return TRUEDIRECTORYITERATOR::ISDOT if the current item is. Or., returns truedirectoryiterator::isexecutable if the file is executable, Returns Truedirectoryiterator::isfile if the file is a regular file, return Truedirectoryiterator::islink if the file is a symbolic link, return Truedirectoryiterator: : isreadable If the file is readable, return truedirectoryiterator::iswritable if the file is writable, return TruediRectoryiterator::key returns the current directory entry Directoryiterator::next moves to the next item Directoryiterator::rewind returns 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"; }} 21. The Recursivedirectoryiterator recursive directory file Walker allows you to list all directory hierarchies instead of just one directory. Method Description Recursivedirectoryiterator::getchildren If this is a directory, return 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 recursivedirectoryiterator: : Rewind Returns the directory pointer to the starting position recursiveiteratoriterator::current accesses the current element value Recursiveiteratoriterator:: Getdepth gets the current depth of the recursive iteration recursiveiteratoriterator::getsubiterator the current active sub-iterator Recursiveiteratoriterator:: Key to access the current key Recursiveiteratoriterator::next move forward to the next element recursiveiteratoriterator:: Rewind returns the iterator to the first element of the top-level inner iterator recursiveiteratoriterator::valid checks whether the current position is legal//lists all files in the specified directory $path = Realpath ('. /'); $objects = new Recursiveiteratoriterator (new Recursivedirectoryiterator ($path), Recursiveiteratoriterator::self_first); foreach ($objectsas $name = $object) {echo "$name \ n"; } 22. Filesystemiterator is the directoryiterator walker $it = new Filesystemiterator (' ... /'); foreach ($itas $fileinfo) {echo$fileinfo->getfilename (). "\ n"; } 23. Globiterator file walker with matching mode//Find out: /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 ()); }}/**output a total of 23 php files [1]. \1.php [2]. \11.php [3]. \12.php [4]. \13.php [5]. \14.php [6]. \15.php [7]. \16.php [8]. \17.php [9]. \19.php []. \2.php [All]. \20.php []. \21.php [\22.php]. \23.php [15]. \24. php [+]. \25.php []. \26.php []. \3.php []. \4.php []. \5.php [22]. \7.php. php [+]. \9.php **/24. Multipleiterator Connector 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); }/**output Array ([ID] = 001 [NAME] = Zhang San [age] = +) Array ( [id] = 002 [name] = John Doe [age] = +) Array ([id] = 003 [name] + = Harry [age] = 11) **/25. RecursivecalLbackfilteriterator (PHP5.4) performs a recursive operation on the Recursiveiterator iterator while performing the filtering and callback operations, 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) {echo$file->getpathname (). Php_eol; } 26. Simplexmliteratorxml document access iterator for access to all nodes in 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); /**output Array ([Book] = Array ([0] = = Array ( [title] = = Array ([0] + = PHP Basics ) [author] = = Array ( [0] = Jim Smith) [1] = + XML Basics ) ) **/