Jump to content

Get Children Of Parent In Multi-Dimensional Array


Hybride

Recommended Posts

I have a multi-dimensional array (something as below). What am trying to do is find a specific value, and if that value has children, list only those children. So for example, if am searching for slug's "test", then all of "test's" children list on the page. "Test2" has no children, so none listed. If am searching for "/test/sub" (the slug), and since it has children, I wanted to show all of the children (eg. "sh", "rd", "co"). I have only a code for checking a multi-dimensional array, but am lost as to how to go beyond that.

function in_array_r($needle, $haystack, $strict = true)
{
foreach ($haystack as $item)
{
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict)))
{
return true;
}
}
return false;
}

 

Array
(
 [test] => Array
	 (
		 [children] => Array
			 (
				 [2] => Array
					 (
						 [parent] => 4
						 [title] => Sub
						 [slug] => test/sub/
						 [id] => 2
						 [children] => Array
							 (
								 [3] => Array
									 (
										 [parent] => 2
										 [title] => sh
										 [slug] => test/sub/sh
										 [id] => 3
									 )
									 [27] => Array
									 (
										 [parent] => 2
										 [title] => RD
										 [slug] => test/sub/rd
										 [id] => 27
									 )
								 [145] => Array
									 (
										 [parent] => 2
										 [title] => cO
										 [slug] => test/sub/co
										 [id] => 145
									 )
							 )
					 )
				 [8] => Array
					 (
						 [parent] => 4
						 [title] => sub2
						 [slug] => test/sub2
						 [id] => 8
					 )
				 [19] => Array
					 (
						 [parent] => 4
						 [title] => sub3
						 [slug] => test/sub3
						 [id] => 19
						 [children] => Array
							 (
								 [20] => Array
									 (
										 [parent] => 19
										 [title] => child1
										 [slug] => test/sub3/child1
										 [id] => 20
									 )
								 [21] => Array
									 (
										 [parent] => 19
										 [title] => child2
										 [slug] => test/sub3/child2
										 [id] => 21
									 )
							 )
					 )

Link to comment
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.