note 102574 modified in class.recursivearrayiterator by danbrown

From: Date: Tue, 22 Feb 2011 15:30:54 +0000
Subject: note 102574 modified in class.recursivearrayiterator by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-177219@lists.php.net to get a copy of this message
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! <?php $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 --was-- 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 http://php.net/manual/en/class.recursivearrayiterator.php

« previous php.notes (#177219) next »