note 102574 added to class.recursivearrayiterator

[email protected] Tue, 22 Feb 2011 07:23:56 -0800
Newsgroups php.notes
Message-ID <[email protected]>
Using the RecursiveArrayIterator to traverse an unknown amount of sub arrays within the outer array. Note: This functionality is already provided by using the RecursiveIteratorIterator but is useful in understanding how to use the iterator when using for the first time as all the terminology does get rather confusing at first sight of SPL!

$myArray = array(
	0 => 'a',
	1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))),
	2 => 'b',
	3 => array('subA','subB','subC'),
	4 => 'c'
);

$iterator = new RecursiveArrayIterator($myArray);
iterator_apply($iterator, 'traverseStructure', array($iterator));

function traverseStructure($iterator) {
	
	while ( $iterator -> valid() ) {

		if ( $iterator -> hasChildren() ) {
		
			traverseStructure($iterator -> getChildren());
			
		}
		else {
			echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;	
		}

		$iterator -> next();
	}
}

The output from which is:
0 : a
0 : subA
1 : subB
0 : subsubA
1 : subsubB
0 : deepA
1 : deepB
2 : b
0 : subA
1 : subB
2 : subC
4 : c
----
Server IP: 69.147.83.197
Probable Submitter: 86.40.5.98
----
Manual Page -- http://www.php.net/manual/en/class.recursivearrayiterator.php
Edit        -- https://master.php.net/note/edit/102574
Del: integrated  -- https://master.php.net/note/delete/102574/integrated
Del: useless     -- https://master.php.net/note/delete/102574/useless
Del: bad code    -- https://master.php.net/note/delete/102574/bad+code
Del: spam        -- https://master.php.net/note/delete/102574/spam
Del: non-english -- https://master.php.net/note/delete/102574/non-english
Del: in docs     -- https://master.php.net/note/delete/102574/in+docs
Del: other reasons-- https://master.php.net/note/delete/102574
Reject      -- https://master.php.net/note/reject/102574
Search      -- https://master.php.net/manage/user-notes.php