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

4
假设我有一个嵌套的/多维数组,如下所示:
array(
   'World'=>array(
            'Asia'=>array(
               'Japan'=>array(
                    'City'=>'Tokyo'
               )
          )
     )
);

我希望能够查找当前城市级别中所有父级。

例如,对于城市,响应应包含一个包含所有父级的数组:

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

那么我如何在嵌套的数组中找到所有父级呢?

1个回答

4

递归是你在这里的好帮手。你需要递归地遍历数组并获取所有的父元素。你的问题在这里有讨论,看一下这个评论。

<?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;
}

?>

你能提供一个如何做到的例子吗? - Zain Reza Merchant
@Zain,我已经包含了讨论此问题的链接,请去那里看看。 - shamittomar
我注意到这个函数不是我想要的方式。它从给定的子键值中搜索键,但我想从子键获取父键。在我写的上面的数组中,如果我想获取亚洲的父键,即世界,我该如何检索? - Zain Reza Merchant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接