如何在 PHP 中按可变量深入到多维数组中?

  • 本文关键字:数组 变量 PHP php arrays variables
  • 更新时间 :
  • 英文 :


我有一个名为$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"
}
}
}
}
}
}

最新更新