How to find all the parent keys of an array from a given child key?

Suppose I have below a nested / multidimensional array:

array( 'World'=>array( 'Asia'=>array( 'Japan'=>array( 'City'=>'Tokyo' ) ) ) ); 

I want to find out all the parents in the heriarchy of the current city.

For example, for a city, the answer should be an array of parents containing:

 array( 'World'=>array( 'Asia'=>array( 'Japan' ) ) ); 

So, how do I find all parents in a chain in a nested array?

+4
source share
1 answer

Recursion is your friend here. You need to go recursively and get all the parents. Your issue is discussed here, look at this comment.

 <?php function getParentStack($child, $stack) { foreach ($stack as $k => $v) { if (is_array($v)) { // If the current element of the array is an array, recurse it and capture the return $return = getParentStack($child, $v); // If the return is an array, stack it and return it if (is_array($return)) { return array($k => $return); } } else { // Since we are not on an array, compare directly if ($v == $child) { // And if we match, stack it and return it return array($k => $child); } } } // Return false since there was nothing found return false; } ?> 
+4
source

Source: https://habr.com/ru/post/1337278/


All Articles