【问题标题】:How can I go deep by a variable amount into a multidimensional array in PHP?如何在 PHP 中以可变数量深入到多维数组中?
【发布时间】:2019-11-29 22:16:51
【问题描述】:

我有一个名为$organized_comments 的多维数组和一个名为$ancestors 的数组,它由一个函数(不重要)给出,该函数列出了$organized_comments 中一个元素的所有祖先。

$organized_comments 看起来像这样:

Array
(
    [1] => Array
        (
            [id] => 1
            [child] => Array
                       (
                           [id] => 2
                           [child] => Array
                                   (
                                   [id] => 3
                                   [child] => Array
                                           (
                                           )
                                   )
                       )
        )
)

我运行我的函数,输入为3,它的输出是$ancestors等于[1,2],这意味着3的祖先从最远到最近是1,然后是2

我想创建一个贯穿$ancestors 的函数,当它到达[id] => 3 时,我可以在[child] 键中插入一个值。

我尝试的是这样的:

$ancestors_count = count($ancestors);
    $i = 0;
    $thing = '$organized_comments';
    foreach($ancestors as $parent_id_here) {
        $i = $i + 1;
        if ($i != $ancestors_count) {
        $thing = $thing . "['$parent_id_here']";
        } else {
        ///MY ACTION
        }
    }

但这显然不起作用,因为我只是添加字符串。我该怎么做才能到达[id] => 3

谢谢!如果我有不清楚的地方,请告诉我。

【问题讨论】:

  • 研究递归
  • 实际上,您正在寻找的可能更符合物化路径

标签: php arrays variables


【解决方案1】:

根据您的$thing 串联逻辑,我得出结论['child'] 只能包含单个元素,并且数组键始终与对应的项目ID 匹配。

echo 'Before: ', json_encode($organized_comments, JSON_PRETTY_PRINT), "\n"; // more readable than print_r()

$ancestors = [1, 2];
$item = &$organized_comments;
foreach ( $ancestors as $ancestor_id ) {
    $item = &$item[$ancestor_id]['child'];
}
if ( $item ) {
    // $id = array_key_first($item); // php 7.3+
    $id   = array_keys($item)[0];
    $item = &$item[$id];
    // do your thing here
    $item['foo'] = 'bar';
}
unset($item); // destroy reference to avoid accidental data corruption later

echo 'After: ', json_encode($organized_comments, JSON_PRETTY_PRINT), "\n";

输出:

Before: {
    "1": {
        "id": 1,
        "child": {
            "2": {
                "id": 2,
                "child": {
                    "3": {
                        "id": 3,
                        "child": []
                    }
                }
            }
        }
    }
}
After: {
    "1": {
        "id": 1,
        "child": {
            "2": {
                "id": 2,
                "child": {
                    "3": {
                        "id": 3,
                        "child": [],
                        "foo": "bar"
                    }
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    相关资源
    最近更新 更多