【发布时间】: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?
谢谢!如果我有不清楚的地方,请告诉我。
【问题讨论】:
-
研究递归
-
实际上,您正在寻找的可能更符合物化路径