Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^154) CHAPTER 10 ■ SPL ITERATORS
Listing 10-12. Using a RecursiveIteratorIterator Iterator
$arr = array(
0 => 'a';
1 => array('a','b','c'),
2 => 'b',
3 => array('a','b','c'),
4 => 'c'
);
$arrayIterator = new RecursiveArrayIterator($arr);
$it = new RecursiveIteratorIterator($arrayIterator);
print_r(iterator_to_array($it, false));
Array
(
[0] => a
[1] => a
[2] => b
[3] => c
[4] => b
[5] => a
[6] => b
[7] => c
[8] => c
)
As you can see, the result of Listing 10-12 is a single-dimensional array.
The signature of the RecursiveIteratorIterator’s constructor is as follows:
__construct (RecursiveIterator $it, $mode=self::LEAVES_ONLY, $flags=0)
The $mode parameter can take one of three class constants: CHILD_FIRST, SELF_FIRST, or the
default LEAVES_ONLY. This mode parameter controls whether the nodes are included in the tree
and in what order. A directory structure, for example, would be best printed as a SELF_FIRST
tree, but when searching for files, LEAVES_ONLY would make more sense.
The $flags parameter can be set to CATCH_GET_CHILDREN, which is used to catch any excep-
tion when trying to call the child iterators and to just proceed to the next element when an
exception is thrown.
RecursiveTreeIterator
The RecursiveTreeIterator is not a built-in iterator, but is a sample iterator that is provided with
the SPL extension in the examples directory, /ext/spl/examples/recursivetreeiterator.inc.
Once included, this iterator will allow you to visualize a tree, as demonstrated in Listing 10-13.
McArthur_819-9C10.fm Page 154 Friday, February 22, 2008 9:08 AM

Free download pdf