加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 17:05:51 所属栏目:PHP教程 来源:网络整理
导读:假设我有以下嵌套/多维数组: array( 'World'=array( 'Asia'=array( 'Japan'=array( 'City'='Tokyo' ) ) )); 我希望能够找到当前城市的所有父母. 例如,对于City,响应应该是包含以下内容的父类数组: array( 'World'=array( 'Asia'=array( 'Japan' ) )); 那么
假设我有以下嵌套/多维数组:

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

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

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

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

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

解决方法

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

?>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读