Jump to content

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

Link to comment
https://forums.phpfreaks.com/topic/210313-tree-recursion/
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.