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
									 )
							 )
					 )

Archived

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

×
×
  • 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.