there is no base case in the printArrayKeysRecursively method;
therefore it is not handling recursion; its just using the
RecursiveArrayItereators public methods. i think that is totally appropriate.
but i believe i understand what youre getting at; namely the
RecursiveArrayIterator implments Iterator, sooo, we should be able
to use the foreach construct in our client code to cleanly iterate over the
object. here is a new revision, which you may like more
than the first one:
<?php
$array = array(
array('name'=>'butch', 'sex'=>'m', 'breed'=>'boxer'),
array('name'=>'fido', 'sex'=>'m', 'breed'=>'doberman'),
array('name'=>'girly','sex'=>'f', 'breed'=>'poodle')
);
$iterator = new RecursiveArrayIterator($array);
foreach($iterator as $outerValue) {
foreach($outerValue as $innerKey => $innerValue) {
echo $innerKey . ' => ' . $innerValue . PHP_EOL;
}
}
?>
notice that there are 2 foreach invocations; those correspond directly to
the levels of nesting in $array. so if you had another level of
nesting in $array, there would have to be another level of nesting in the
foreach invocations (if you want to do something w/ those values). that
brings us to RecursiveIteratorIterator
which quoting Harry Fuecks in his article on
SPL<http://www.sitepoint.com/article/php5-standard-library>
*RecursiveIteratorIterator: this helps you do cool stuff like "flatten" a
hierarchical data structure so that you can loop through it with a single
foreach statement, while still preserving knowledge of the hierarchy. This
class could be very useful for rendering tree menus, for example.
*as i understand it RecursiveIteratorIterator essentially allows you to
define a particular action depending on which level of children is currently
being operated on. so i think the decision to use that over
RecursiveArrayIterator comes down to the number of levels of nesting that
will be in your data structure. if it will always be 2 levels (or a static
number of levels that is relatively small), stick w/ RecursiveArrayIterator,
otherwise if the number of nested levels is going to vary (or be more than a
few), i think, thats when you need to consider RecursiveIteratorIterator.
-nathan
note: im still a newb on spl myself :)
On 7/22/07, Kevin Waterson <[EMAIL PROTECTED]> wrote:
This one time, at band camp, "Nathan Nobbe" <[EMAIL PROTECTED]>
wrote:
Thanks for the response.
I was hoping to avoid this sort of recursion within userspace and keep
it at a lower level. Should not the recursive iterator recurse so we
dont need to be using user defined functions?
> printArrayKeysRecursively($innerRecursiveArrayIterator); // handle
printing
Kind regards
Kevin
--
"Democracy is two wolves and a lamb voting on what to have for lunch.
Liberty is a well-armed lamb contesting the vote."
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php