droc60607 2009-12-27 20:45
浏览 13
已采纳

通过参数访问php数组子?

I have a unique case where I have an array like so:

$a = array('a' => array('b' => array('c' => 'woohoo!')));

I want to access values of the array in a manner like this:

  • some_function($a, array('a')) which would return the array for position a
  • some_function($a, array('a', 'b', 'c')) which would return the word 'woohoo'

So basically, it drills down in the array using the passed in variables in the second param and checks for the existence of that key in the result. Any ideas on some native php functions that can help do this? I'm assuming it'll need to make use of recursion. Any thoughts would be really appreciated.

Thanks.

  • 写回答

4条回答 默认 最新

  • dreamone5156 2009-12-27 20:52
    关注

    This is untested but you shouldn't need recursion to handle this case:

    function getValueByKey($array, $key) {
        foreach ($key as $val) {
            if (!empty($array[$val])) {
                $array = $array[$val];
            } else return false;
        }
        return $array;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀