Zain Reza Merchant
Zain Reza Merchant

Reputation: 43

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

Let's suppose I have below nested/multi-dim array:

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

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

For example, for the City, the response should be an array of parents containing:

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

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

Upvotes: 4

Views: 4976

Answers (1)

shamittomar
shamittomar

Reputation: 46692

Recursion is your friend here. You need to traverse the array recursively and get all the parents. Your problem is discussed here, take a 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;
}

?>

Upvotes: 4

Related Questions