我怀疑我在这里做了些蠢事,但我对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);
答案 0 :(得分:5)
普通数组中的值似乎无法修改,因为它们无法通过引用ArrayIterator
的构造函数传递(RecursiveArrayIterator
从此类继承其offset*()
方法,见SPL Reference)。因此,对offsetSet()
的所有调用都会对数组的副本起作用。
我猜他们选择避免调用引用,因为它在面向对象的环境中没有多大意义(即传递ArrayObject
的实例时应该是默认情况)。
更多代码来说明这一点:
$a = array();
// Values inside of ArrayObject instances will be changed correctly, values
// inside of plain arrays won't
$a[] = array(new ArrayObject(range(100, 200, 100)),
new ArrayObject(range(200, 100, -100)),
range(100, 200, 100));
$a[] = new ArrayObject(range(225, 75, -75));
// The array has to be
// - converted to an ArrayObject or
// - returned via $it->getArrayCopy()
// in order for this field to get handled properly
$a[] = 199;
// These values won't be modified in any case
$a[] = range(100, 200, 50);
// Comment this line for testing
$a = new ArrayObject($a);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
foreach ($it as $k => $v) {
// getDepth() returns the current iterator nesting level
echo $it->getDepth() . ': ' . $it->current();
if ($v < 200) {
echo "\ttrue";
// This line is equal to:
// $it->getSubIterator($it->getDepth())->offsetSet($k, 0);
$it->getInnerIterator()->offsetSet($k, 0);
}
echo ($it->current() == 0) ? "\tchanged" : '';
echo "\n";
}
// In this context, there's no real point in using getArrayCopy() as it only
// copies the topmost nesting level. It should be more obvious to work with $a
// itself
print_r($a);
//print_r($it->getArrayCopy());
答案 1 :(得分:3)
不使用Iterator类(似乎复制 RecursiveArrayIterator::beginChildren()
上的数据而不是通过引用传递。)
您可以使用以下内容实现您的目标
function drop_200(&$v) { if($v < 200) { $v = 0; } }
$aNestedArray = array();
$aNestedArray[101] = range(100, 1000, 100);
$aNestedArray[201] = range(300, 25, -25);
$aNestedArray[301] = range(500, 0, -50);
array_walk_recursive ($aNestedArray, 'drop_200');
print_r($aNestedArray);
或使用create_function()
而不是创建drop_200函数,但您的里程可能因create_function和内存使用而异。
答案 2 :(得分:2)
看起来getInnerIterator会创建子迭代器的副本。
也许有不同的方法? (请继续关注..)
更新:在黑客入侵一段时间之后,又吸引了其他3位工程师,看起来好像PHP没有办法改变subIterator的值。
您可以随时使用旧支架:
<?php
// Easy to read, if you don't mind references (and runs 3x slower in my tests)
foreach($aNestedArray as &$subArray) {
foreach($subArray as &$val) {
if ($val < 200) {
$val = 0;
}
}
}
?>
OR
<?php
// Harder to read, but avoids references and is faster.
$outherKeys = array_keys($aNestedArray);
foreach($outherKeys as $outerKey) {
$innerKeys = array_keys($aNestedArray[$outerKey]);
foreach($innerKeys as $innerKey) {
if ($aNestedArray[$outerKey][$innerKey] < 200) {
$aNestedArray[$outerKey][$innerKey] = 0;
}
}
}
?>
答案 3 :(得分:2)
首先将数组转换为对象,然后按预期工作..
$array = [
'one' => 'One',
'two' => 'Two',
'three' => [
'four' => 'Four',
'five' => [
'six' => 'Six',
'seven' => 'Seven'
]
]
];
// Convert to object (using whatever method you want)
$array = json_decode(json_encode($array));
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key => $value) {
$iterator->getInnerIterator()->offsetSet($key, strtoupper($value));
}
var_dump($iterator->getArrayCopy());
答案 4 :(得分:1)
您需要在当前深度调用getSubIterator
,在该深度使用offsetSet
,并对返回树上的所有深度执行相同操作。
这对于在数组或数组中的值上进行无限级别数组合并和替换非常有用。不幸的是,array_walk_recursive
在这种情况下不起作用,因为该函数只访问叶节点 ..所以永远不会访问下面$ array中的'replace_this_array'键。
例如,要更新数组中未知级别的所有值,但只有那些包含某个键的值,您将执行以下操作:
$array = [
'test' => 'value',
'level_one' => [
'level_two' => [
'level_three' => [
'replace_this_array' => [
'special_key' => 'replacement_value',
'key_one' => 'testing',
'key_two' => 'value',
'four' => 'another value'
]
],
'ordinary_key' => 'value'
]
]
];
$arrayIterator = new \RecursiveArrayIterator($array);
$completeIterator = new \RecursiveIteratorIterator($arrayIterator, \RecursiveIteratorIterator::SELF_FIRST);
foreach ($completeIterator as $key => $value) {
if (is_array($value) && array_key_exists('special_key', $value)) {
// Here we replace ALL keys with the same value from 'special_key'
$replaced = array_fill(0, count($value), $value['special_key']);
$value = array_combine(array_keys($value), $replaced);
// Add a new key?
$value['new_key'] = 'new value';
// Get the current depth and traverse back up the tree, saving the modifications
$currentDepth = $completeIterator->getDepth();
for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--) {
// Get the current level iterator
$subIterator = $completeIterator->getSubIterator($subDepth);
// If we are on the level we want to change, use the replacements ($value) other wise set the key to the parent iterators value
$subIterator->offsetSet($subIterator->key(), ($subDepth === $currentDepth ? $value : $completeIterator->getSubIterator(($subDepth+1))->getArrayCopy()));
}
}
}
return $completeIterator->getArrayCopy();
// return:
$array = [
'test' => 'value',
'level_one' => [
'level_two' => [
'level_three' => [
'replace_this_array' => [
'special_key' => 'replacement_value',
'key_one' => 'replacement_value',
'key_two' => 'replacement_value',
'four' => 'replacement_value',
'new_key' => 'new value'
]
],
'ordinary_key' => 'value'
]
]
];
答案 5 :(得分:0)
我知道这不会直接回答你的问题,但是在迭代过程中修改迭代后的对象并不是一个好习惯。
答案 6 :(得分:0)
它可以归结为通过引用传递vs传递值吗?
例如尝试更改:
$cArray = new ArrayObject($aNestedArray);
为:
$cArray = new ArrayObject(&$aNestedArray);