使用 PHP 数组作为索引路径
我在平面 PHP 数组中有一个分层数组路径,例如: $path = array('fruit', 'banana', 'fresh');
我将多维数组定义为 $tree
。您将如何使用$path
来设置/获取$tree
中的适当节点? $tree[$path] = 'blablabl';
抛出“非法偏移错误”。我不确定如何 implode() 到字符串的路径并使用 eval() 来获取索引。最直接的方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为数组就是数组,而 PHP 对树一无所知,因此您必须自己根据多维数组解析路径,但这并不难。
迭代
或递归
注意,这是最简单的解决方案。例如,在尝试访问
$path
中的给定密钥之前,您应该注意它是否存在。更新:我忽略了问题中的“设置”部分。如果没有引用,那就没那么有趣了,因此我建议完全切换到对象而不是数组。您不需要创建一个类。您可以简单地使用
stdClass
。这甚至感觉有点“树”式Because an array is an array and PHP doesn't know anything about trees you must resolve the path against your multidimensional array yourself, but thats not hard.
Iterativ
or recursive
Note, that this are the simplest solutions. For example you should take care, that a given key from
$path
exists, before you try to access it.Update: I overlooked the "set"-part in the question. Without references its not that funny, thus I suggest to completely switch over to objects instead of arrays. Its not required, that you create a class. You can simply use
stdClass
. This would even feel a little bit more "tree"ish我通过引用解决了同样的问题:
将产生
注意,由于 PHP autovivicates 这将创建任何非 -现有的键可以是一个数组,唯一的键是路径中的下一个元素,如果是叶节点,则为 null。幸运的是,这正是我需要的行为。然而,我仍然觉得有点尴尬,因为我必须用一种如此专注于数组的语言自己编写这个函数。非常欢迎任何缩短此时间的建议。
I solved the same problem with references:
will produce
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.