我的问题非常类似于:Multidimensional Arrays Nested to Unlimited Depth
上面问题中的This answer适用于遍历,但我需要修改循环内数组中的值。
$depth = 2; // This is actually a method argument passed at runtime
$it = new \RecursiveIteratorIterator(
new \RecursiveArrayIterator($arr),
\RecursiveIteratorIterator::SELF_FIRST
);
$it->setMaxDepth($depth);
// PHP Fatal error: An iterator cannot be used with foreach by reference
foreach ($it as $key => &$value) {
if ($it->getDepth() === $depth - 1) {
$value = 'foo';
}
}
// I also tried this, which gives:
// PHP Fatal error: Cannot use object of type RecursiveIteratorIterator as array
foreach ($it as $key => $value) {
if ($it->getDepth() === $depth - 1) {
$it[$key] = 'foo';
}
}
如何在遍历时改变数组?