如何从给定的子键中查找数组的所有父键?

时间:2011-01-27 08:23:36

标签: php

假设我有以下嵌套/多维数组:

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

我希望能够找到当前城市的所有父母。

例如,对于City,响应应该是包含以下内容的父类数组:

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

那么如何在嵌套数组中找到链中的所有父元素?

1 个答案:

答案 0 :(得分:4)

递归是你的朋友。您需要递归遍历数组并获取所有父项。 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;
}

?>