dongtieshang5429 2011-07-11 21:24
浏览 36
已采纳

使用PHP数组作为索引路径

I have a hierarchical array path in a flat PHP array, e.g.: $path = array('fruit', 'banana', 'fresh');

I define my multidimensional array as $tree. How would you use $path to set/get the appropriate node in $tree? $tree[$path] = 'blablabl'; throws an "Illegal offset error". I'm not sure how I would implode() the path to a string and use eval() to get the index. What's the most straightforward way to do this?

  • 写回答

2条回答 默认 最新

  • dq05304 2016-06-13 20:31
    关注

    I solved the same problem with references:

    function &walk_path(array &$root, array $path)
    {
        $cursor = &$root;
        foreach ($path as $e) { $cursor = &$cursor[$e]; }
        return $cursor;
    }
    
    $db = [];
    $tmp = &walk_path($db, ["users","deanna", "favourite food"]);
    $tmp = "chocolate";
    print_r($db);
    

    will produce

    Array
    (
        [users] => Array
            (
                [deanna] => Array
                    (
                        [favourite food] => chocolate
                    )
    
            )
    
    )
    

    Note that since PHP autovivicates this will create any non-existent keys either as an array with the only key being the next elemenet in the path or null if it is the leaf node. This is fortunately exactly the behaviour I needed. However, it still strikes me as a bit akward that I have to write this function myself in a lanuage so focused on its arrays. Any suggestions to make this shorter are very welcome.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置