我怀疑我在这里做了一些愚蠢的事情,但我对 SPL 的一个简单问题感到困惑:
如何使用RecursiveArrayIterator / RecursiveIteratorIterator修改数组的内容(本例中的值) ?
使用以下测试代码,我可以使用getInnerIterator()和offsetSet()更改循环内的值,并在循环内转储修改后的数组。
但是当我离开循环并从迭代器中转储数组时,它又回到了原始值。发生了什么?
$aNestedArray = array();
$aNestedArray[101] = range(100, 1000, 100);
$aNestedArray[201] = range(300, 25, -25);
$aNestedArray[301] = range(500, 0, -50);
$cArray = new ArrayObject($aNestedArray);
$cRecursiveIter = new RecursiveIteratorIterator(new RecursiveArrayIterator($cArray), RecursiveIteratorIterator::LEAVES_ONLY);
// Zero any array elements under 200
while ($cRecursiveIter->valid())
{
if ($cRecursiveIter->current() < 200)
{
$cInnerIter = $cRecursiveIter->getInnerIterator();
// $cInnerIter is a RecursiveArrayIterator
$cInnerIter->offsetSet($cInnerIter->key(), 0);
}
// This returns the modified array as expected, with elements progressively being zeroed
print_r($cRecursiveIter->getArrayCopy());
$cRecursiveIter->next();
}
$aNestedArray = $cRecursiveIter->getArrayCopy();
// But this returns the original array. Eh??
print_r($aNestedArray);