如何在使用递归数组生成器时更改数组键和值?
2022-08-31 01:08:53
我怀疑我在这里做了一些愚蠢的事情,但我对SPL似乎很简单的问题感到困惑:
如何使用递归数组/递归迭代器修改数组的内容(此示例中的值)?
使用下面的测试代码,我可以使用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);