Re: RecursiveArrayIterator

From: Date: Sun, 22 Jul 2007 17:26:41 +0000
Subject: Re: RecursiveArrayIterator
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-259342@lists.php.net to get a copy of this message
Kevin, im not sure why you need the RecursiveIteratorIterator; the RecursiveArrayIterator is capable of handling the nested arrays by itself. here is a revision of the code you posted, using PHP_EOL for newlines since i developed this via the CLI. <?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); printArrayKeysRecursively($iterator); function printArrayKeysRecursively(RecursiveArrayIterator $theRecursiveArrayIterator) { while($theRecursiveArrayIterator->valid()) { /// handle the current node if($theRecursiveArrayIterator->hasChildren()) { // determine if the algorithm should recurse to a child $innerRecursiveArrayIterator = $theRecursiveArrayIterator->getChildren(); printArrayKeysRecursively($innerRecursiveArrayIterator); // handle printing of children } else { // print current node echo $theRecursiveArrayIterator->key() . ' => ' . $theRecursiveArrayIterator->current() . PHP_EOL; } $theRecursiveArrayIterator->next(); // move to the next node } } ?> here is the output on my box: nathan@nnppc ~ $ php testRecursiveIterator.php name => butch sex => m breed => boxer name => fido sex => m breed => doberman name => girly sex => f breed => poodle - nathan On 7/22/07, Kevin Waterson <kevin@oceania.net> wrote:
When I run the code below, I get an output of the array which is good. But the first member of the array output is 0=>Array. Is there a way to prevent this? eg: 0 -- Array name -- butch sex -- m breed -- boxer name -- fido sex -- m breed -- doberman name -- girly sex -- f breed -- poodle <?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 RecursiveIteratorIterator(new RecursiveArrayIterator($array)); while($iterator->valid())
    {
    echo $iterator->key().' -- '.$iterator->current().'<br/>';
    $iterator->next();
    }
?> 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


« previous php.general (#259342) next »