修改未知深度的多维数组

时间:2016-05-11 04:34:50

标签: php arrays recursion multidimensional-array iterator

我的问题非常类似于: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';
    }
}

如何在遍历时改变数组?

0 个答案:

没有答案