Php-SPL Library iterator class-php Tutorial

Source: Internet
Author: User
Php-SPL Library iterator class
SPL provides multiple iterator classes, including iterative access, data filtering, cache results, and paging control ., Because php is always growing, I try to list all iteration classes in SPL. Some of the following iterator classes require php5.4, and some other classes such as SearhIteratoer have been removed in the latest php version. arrayIteratoer creates an Iterator from the PHP array. when used together with the IteratorAggregate class, it eliminates the need to directly implement the Iterator interface.
 <示例>
  
$ B = array ('name' => 'mengzhi', 'age' => '12', 'City' => 'Shanghai '); $ a = new ArrayIterator ($ B); $ a-> append (array ('Home' => 'China', 'Work' => 'developer ')); $ c = $ a-> getArrayCopy (); print_r ($ a); print_r ($ c);/** output ArrayIterator Object ([storage: ArrayIterator: private] => Array ([name] => mengzhi [age] => 12 [city] => shanghai [0] => Array ([home] => china [work] => developer ))) array ([name] => mengzhi [age] => 12 [city] => shanghai [0] => Array ([home] => china [work] => developer)) **/2. limitIterator returns the given number of results and the starting index points of the results retrieved from the set:
  <示例>
   
// Create an iterator to be limited $ fruits = new ArrayIterator (array ('apple', 'bana', '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) as $ fruit) {print_r ($ fruit );}/ ** Output string (5) "apple" string (6) "banana" string (6) "cherry" cherrydamsonelderberry */3. AppendIterator iteratively accesses several different Iterators in sequence. For example, you want to iteratively access two or more combinations in a loop. The append method of this iterator is similar to the array_merge () function to merge arrays. $ 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. based on the OuterIterator interface, FilterIterator is used to filter data and return qualified elements. An abstract method accept () must be implemented. this method must return true or false for the current entry 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 = ar Ray (array ('name' => 'Jonathan ', 'id' => '5'), array ('name' => 'Abdul ', 'id' => '22'); $ object = new ArrayObject ($ array ); // remove a person named abdul $ iterator = new UserFilter ($ object-> getIterator (), 'Abdul'); foreach ($ iteratoras $ result) {echo $ result ['name'];}/** output Jonathan **/5. regexIterator inherits FilterIterator and supports regular expression pattern matching and modifying the elements in the iterator. It 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 general type iterator. all classes that implement the Traversable interface can be accessed by it through iteration. 7. CachingIterator is used to read an element in advance. for example, it can be used to determine whether the current element is the last element. $ Array = array ('koala ', 'hangaroo', 'Wombat', 'Wallaby', 'emu', 'kiw', '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 an iterator for non-sequential access, allowing hops Go 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 a set that cannot be iterated multiple times. it is applicable to performing one-time operations during the iteration process. $ Fruit = array ('apple', 'bana', '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 is a placeholder iterator that does not perform any operations. This iterator can be used to implement an abstract class method and return an iterator. 11. InfiniteIterator is used to continuously access data. when the last element is iterated, the access is iterated 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 **/12. recursiveArrayIterator creates an iterator for recursive array structures, similar to multi-dimensional arrays. it provides the required operations for many more complex iterators, such as RecursiveTreeIterator and RecursiveIteratorIterator iterator. $ Fruits = array ("a" => "lemon", "B" => "orange", array ("a" => "apple ", "p" => "pear"); $ iterator = new RecursiveArrayIterator ($ fruits); while ($ iterator-> valid ()) {// check whether the subnode if ($ iterator-> hasChildren () {// output so the byte points 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" => "orange", array ("a" => "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 **/14. recursi VeTreeIterator displays a tree structure visually. $ Hey = array ("a" => "lemon", "B" => "orange", array ("a" => "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 \-pear **/15. parentIterator is an extended FilterIterator iterator that filters out non-parent elements from the RecursiveIterator iterator and only finds the key values of the child nodes. In general, it is to remove branches and leave leaves. $ Hey = array ("a" => "lemon", "B" => "orange", array ("a" => "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 a recursive form of the FilterIterator iterator. It also requires the implementation of the abstract accept () method. However, you should use $ this-> getInnerIterator () In this method () method to access the iterator currently being iterated. Class TestsOnlyFilter extends RecursiveFilterIterator {publicfunction accept () {// find the element return $ this-> hasChildren () | (mb_strpos ($ this-> current (), "Ye ")! = FALSE) ;}}$ array = array ("Ye 1", array ("Li 2", "Ye 3", "Ye 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. the RecursiveRegexIterator is a recursive form of the RegexIterator iterator. it only accepts the RecursiveIterator iterator as the iteration object. $ RArrayIterator = new RecursiveArrayIterator (array ('leaf 1', array ('tet3', 'leaf 4', 'leaf 5 '))); $ rRegexIterator = new RecursiveRegexIterator ($ rArrayIterator, '/^ leaf/', attributes: ALL_MATCHES); foreach ($ rRegexIteratoras $ key1 => $ value1) {if ($ rRegexIterator-> hasChildren () {// print all children echo "Children:"; foreach ($ rRegexIterator-> getChildren () as $ key => $ value) {echo $ value. "";} ec Ho "\ n" ;}else {echo "No children \ n" ;}}/** output No children Children: Leaves 4 leaves 5 **/18. the RecursiveCachingIterator performs a recursive operation on the RecursiveIterator iterator to read an element in advance. 19. CallbackFilterIterator (PHP5.4) simultaneously performs filtering and callback operations. after a matching element is found, the callback function is called. $ Hey = array ("li 1", "Ye 2", "Ye 3", "Ye 4", "Ye 5", "Ye 6 ",); $ arrayIterator = new RecursiveArrayIterator ($ hey); function isYe ($ current) {return mb_strpos ($ current, 'Ye ')! = False;} $ rs = new CallbackFilterIterator ($ arrayIterator, 'isye '); print_r (iterator_to_array ($ rs )); /** output Array ([0] => leaf 2 [1] => leaf 3 [2] => leaf 4 [3] => leaf 5 [4] => leaf 6) **/20. directoryIterator directory file traversal 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, tr is returned. UeDirectoryIterator: isFile if the file is a regular file, trueDirectoryIterator: isLink if the file is a symbolic link, trueDirectoryIterator: isReadable if the file is readable, trueDirectoryIterator :: isWritable if the file is writable, return trueDirectoryIterator: key to return the current directory item DirectoryIterator: next to the next DirectoryIterator: rewind to return the directory pointer to the start position DirectoryIterator :: valid check if the directory contains more $ it = new DirectoryIterator (".. /"); foreach ($ itas $ file) {// filter". and... "Directory if (! $ It-> isDot () {echo $ file. "\ n" ;}} 21. the RecursiveDirectoryIterator Recursive directory file traversal tool allows you to list all directory hierarchies, instead of only one directory. Method description RecursiveDirectoryIterator: getChildren if this is a directory, return an iterator for the current item RecursiveDirectoryIterator: hasChildren to return whether the current item is a directory instead. or .. recursiveDirectoryIterator: key returns the path and file name of the current directory item RecursiveDirectoryIterator: next move to the next RecursiveDirectoryIterator: rewind returns the directory pointer to the start position when: current accesses the current element value:: getDepth get the current depth of recursive iteration RecursiveIteratorIterator: getSubIterator get the current active sub-iterator RecursiveI TeratorIterator: key to access the current key RecursiveIteratorIterator: next forward to the next element RecursiveIteratorIterator: rewind returns the iterator to the first element RecursiveIteratorIterator :: valid check whether the current location is legal // list 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 Di RectoryIterator traversal tool $ it = new FilesystemIterator ('.. /'); foreach ($ itas $ fileinfo) {echo $ fileinfo-> getFilename (). "\ n" ;}23. globIterator with file traversal in 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 [10]. \ 2.php [11]. \ Alibaba PHP [12]. \ 21.php [13]. \ 22.php [14]. \ 23.php [15]. \ 24.ph P [16]. \ 25.php [17]. \ 26.php [18]. \ 3.php [19]. \ 4.php [20]. \ 5.php [21]. \ 7.php [22]. \ 8.php [23]. \ 9.php **/24. multipleIterator is used for the iterator connector. for details, see the example $ person_id = new ArrayIterator (array ('001', '002', '002 ')); $ person_name = new ArrayIterator (array ('Zhang San', 'Li Si', 'Wang Wu'); $ person_age = new ArrayIterator (array (22, 23, 11 )); $ mit = new MultipleIterator (MultipleIterator: MIT_KEYS_ASSOC); $ mit-> attachIterat Or ($ 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] => 22) array ([ID] => 002 [NAME] => Li Si [AGE] => 23) array ([ID] => 003 [NAME] => Wang Wu [AGE] => 11) **/25. recursiveCallbackFilterIterator (PHP5 4) perform recursive operations on the RecursiveIterator iterator and perform filtering and callback operations at the same time. after a matching element is found, the callback function is called. 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 file access iterator, which can access all nodes in xml $ xml = <
            
                 
     PHP BasicsJim Smith         
             
    
     
XML basics
         XML; // SimpleXML convert 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 $ ;} $ 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 ))**/
   
  
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.