Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 10 ■ SPL ITERATORS^153

RecursiveArrayIterator
The RecursiveArrayIterator allows you to create an iterator for recursive array structures. This
is an important iterator, as it allows for the operation of many of the more complicated iterators
like RecursiveTreeIterator and RecursiveIteratorIterator. Listing 10-11 demonstrates using
a RecursiveArrayIterator.

Listing 10-11. Using a RecursiveArrayIterator Iterator

$arr = array(
0 => 'a';
1 => array('a','b','c'),
2 => 'b',
3 => array('a','b','c'),
4 => 'c'
);

$it = new RecursiveArrayIterator($arr);
print_r(iterator_to_array($it));

Array
(
[0] => a
[1] => Array
(
[0] => a
[1] => b
[2] => c
)

[2] => b
[3] => Array
(
[0] => a
[1] => b
[2] => c
)

[4] => c
)

RecursiveIteratorIterator
The RecursiveIteratorIterator is actually one of the more useful iterators. It allows you to
take a tree structure and flatten it into a single dimension. When the iterator finds a child iterator,
it is traversed.
Observe the difference between the results of Listing 10-11 and Listing 10-12.

McArthur_819-9C10.fm Page 153 Friday, February 22, 2008 9:08 AM

Free download pdf