Pro PHP- Patterns, Frameworks, Testing and More

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

■Note If your PHP installation is from package management, you can still use the files in the examples
directory by downloading the PHP source distribution for your PHP version. You do not need to compile/reinstall
PHP for these examples to function properly.

Listing 10-13. Using the Sample RecursiveTreeIterator Iterator

require_once('/path/to/php-src/ext/spl/examples/recursivetreeiterator.inc');

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

$arrayIterator = new RecursiveArrayIterator($arr);

$it = new RecursiveTreeIterator($arrayIterator);

print_r(iterator_to_array($it, false));

Array
(
[0] => |-a
[1] => |-Array
[2] => | |-a
[3] => | |-b
[4] => | \-c
[5] => |-b
[6] => |-Array
[7] => | |-a
[8] => | |-b
[9] => | \-c
[10] => \-c
)

RecursiveTreeIterator, like all the included sample iterators, is designed to be extended.
There is no requirement that the tree iterator must output text-based delimiters. It is possible
to construct an iterator that outputs an HTML tree.

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

Free download pdf