douzhang3822 2013-06-13 16:26
浏览 38
已采纳

PHP:从嵌套关联数组中查找动态元素

I'm working on a function that looks like this:

public function myfunction($mainArr, $keys) {
    // $mainArr: a nested associative array
    // $keys: a simple array of strings, example: array('string_1', 'string_2', 'string_3')
    $totalKeys = count(keys);
    if(totalKeys == 1) {
        return mainArr[keys[0]];
    } else if(totalKeys == 2) {
        return mainArr[keys[0]][keys[1]];
    } else if(totalKeys == 3) {
        return mainArr[keys[0]][keys[1]][keys[2]];
    } else if(totalKeys == 4) {
        return mainArr[keys[0]][keys[1]][keys[2]][keys[3]];
    } else if(totalKeys == 5) {
        return mainArr[keys[0]][keys[1]][keys[2]][keys[3]][keys[4]];
    }
    // the same pattern continues..
}

I want to change this function into something more dynamic rather than a big list of "if" conditions, is it possible somehow?

  • 写回答

1条回答 默认 最新

  • dousuo2812 2013-06-13 16:37
    关注

    You can do it for example this way:

    function get_value(array $source, array $keys) {
        foreach ($keys as $key) {
            if (isset($source[$key])) {
                $source = $source[$key];
            }
            else {
                return null;
            }
        }
    
        return $source;
    }
    

    If $keys describes an invalid path inside $source then null will be returned.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信