douluogu8713 2013-04-25 18:47
浏览 64
已采纳

是否有可能将变量计算为多维PHP数组索引

Given a multidimensional array or dictionary $array.

And assuming that $array['foo']['bar']['baz'] = 'something';

Is there a way other than via an eval statement for me use the multi-dimentional index foo/bar/baz? (The use case is in creating the index dynamically i.e. The function does not know what /foo/bar/baz/ is).

The only way I could figure to do this was:

$item = testGetIndex($array, "'foo']['bar']['baz'");

function testGetIndex($array, $index) {
  eval('$item = $array[' . $index . '];');
  return $item;
}

Note: I should mention that I do not want to search this array. This is a weird use case. I am being passed a very large multi dimensional array and it's ugly to have to use constructs like..

$array[foo][bar]..[baz] to make modifications to the array.

  • 写回答

3条回答 默认 最新

  • du229908 2013-04-25 18:53
    关注

    To modify an array using a path:

    function setPath(&$root, $path, $value)
    {
            $paths = explode('/', $path);
            $current = &$root;
    
            foreach ($paths as $path) {
                    if (isset($current[$path])) {
                            $current = &$current[$path];
                    } else {
                            return null;
                    }
            }
    
            return $current = $value;
    }
    $path = 'foo/bar/baz';
    $root = array('foo' => array('bar' => array('baz' => 'something')));
    
    setPath($root, $path, '123');
    

    You can tweak the function to just return a reference to the element you wish to change:

    function &getPath(&$root, $path)
    {
            $paths = explode('/', $path);
            $current = &$root;
    
            foreach ($paths as $path) {
                    if (isset($current[$path])) {
                            $current = &$current[$path];
                    } else {
                            return null;
                    }
            }
    
            return $current;
    }
    
    $x = &getPath($root, $path);
    
    $x = 456; // $root['foo']['bar']['baz'] == 456
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面