virtualvinodh Posted August 10, 2010 Share Posted August 10, 2010 Hi, I wrote a piece of code for doing a recursive printing of all the leaf nodes. But it is not moving beyond one or two levels. Here is the code: $root = array( "paa" => array ( "adi1" => array ( "cir1" => array ( "aka", "ra", "vinodh","dkido" ), "cir2" => array ( "muta", "la" ), "cir3" => array ( "ezut", "telAm" ), "cir4" => array ( "ati" ) ), "adi2" => array ( "cir1" => array ( "paka", "vaV" ), "cir2" => array ( "mutaR", "RE" ), "cir3" => array ( "ula", "ku" ) ) ) ); function traverse($ar) { foreach($ar as $key=>$value) { echo "inside loop of ".$key."<br/>"; if(is_array($value)) { return traverse($value); } else { echo $key."==>".$value."<br/>"; } } } traverse($root); The output I get is: inside loop of paa inside loop of adi1 inside loop of cir1 inside loop of 0 0==>aka inside loop of 1 1==>ra inside loop of 2 2==>vinodh inside loop of 3 3==>dkido It does not seem to visit the other nodes. Anything I missed here ? V Quote Link to comment https://forums.phpfreaks.com/topic/210313-tree-recursion/ Share on other sites More sharing options...
ignace Posted August 10, 2010 Share Posted August 10, 2010 $iterator = new RecursiveArrayIterator($root); foreach(new RecursiveIteratorIterator($iterator) as $node){ echo $node->current(), "<br>\n"; } Quote Link to comment https://forums.phpfreaks.com/topic/210313-tree-recursion/#findComment-1097449 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.