使用 PHP 数组作为索引路径

发布于 2024-11-19 16:06:33 字数 285 浏览 0 评论 0原文

我在平面 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终止放荡 2024-11-26 16:06:34

因为数组就是数组,而 PHP 对树一无所知,因此您必须自己根据多维数组解析路径,但这并不难。

迭代

$result = $tree;
foreach ($path as $step) {
  $result = $result[$step];
}

或递归

function resolve_tree ($tree, $path) {
  return empty($path)
         ? $tree
         : resolve_tree ($tree[$path[0]], array_slice($path, 1));
}

注意,这是最简单的解决方案。例如,在尝试访问 $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

$result = $tree;
foreach ($path as $step) {
  $result = $result[$step];
}

or recursive

function resolve_tree ($tree, $path) {
  return empty($path)
         ? $tree
         : resolve_tree ($tree[$path[0]], array_slice($path, 1));
}

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

枯寂 2024-11-26 16:06:34

我通过引用解决了同样的问题:

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);

将产生

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

        )

)

注意,由于 PHP autovivicates 这将创建任何非 -现有的键可以是一个数组,唯一的键是路径中的下一个元素,如果是叶节点,则为 null。幸运的是,这正是我需要的行为。然而,我仍然觉得有点尴尬,因为我必须用一种如此专注于数组的语言自己编写这个函数。非常欢迎任何缩短此时间的建议。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文