我有一个名为$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
?
谢谢! 请告诉我,如果我在任何时候都不清楚。
根据你的$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"
}
}
}
}
}
}