Jump to content

Archived

This topic is now archived and is closed to further replies.

virtualvinodh

Tree Recursion

Recommended Posts

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

Share this post


Link to post
Share on other sites
$iterator = new RecursiveArrayIterator($root);
foreach(new RecursiveIteratorIterator($iterator) as $node){
  echo $node->current(), "<br>\n";
}

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.