有没有办法改变array_reduce在 PHP 中使用的数组?我正在尝试做这样的事情:给定一些ids 的有序列表:$array = [["id" => 1], ["id" => 13], ["id" => 4]];以及一棵具有与相应ids匹配的子树的树:$tree = [ "id" => 2334, "children" => [ [ "id" => 111, "children" => [] ], [ "id" => 1, // <- this is a match "children" => [ [ "id" => 13, // <- this is a match "children" => [ [ "id" => 4, // <- this is a match "children" => [] ], [ "id" => 225893, "children" => [] ], [ "id" => 225902, "children" => [] ] ] ] ] ] ]];如何改变该子树中的数组?我目前正在尝试使用array_reduce走下树并对其进行变异。但是,突变并未应用于最初传入的$tree.array_reduce($array, function (&$acc, $item) { $index = array_search($item['id'], array_column($acc['children'], 'id')); $acc['children'][$index]['mutated'] = true; // mutation here return $acc['children'][$index];}, $tree);echo "<pre>";var_dump($tree); // $tree is unchanged hereecho "</pre>";$tree上面运行后为什么不变异array_reduce?foreach在这种情况下有没有办法使用?
1 回答
- 1 回答
- 0 关注
- 173 浏览
添加回答
举报
0/150
提交
取消