RecusiveIteratorIterator 与 RecursiveArrayIterator 结合使用的一个非常有用的用例是替换多维数组中任何深度的数组值。
通常,`array_walk_recursive` 用于替换数组深层的值,但不幸的是,这只有在存在标准键值对时才有效 - 换句话说,`array_walk_recursive` **只访问叶子节点,而不是数组**。
所以为了解决这个问题,可以使用迭代器,方法如下:
<?php
$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);
$recursiveIterator = new \RecursiveIteratorIterator($arrayIterator, \RecursiveIteratorIterator::SELF_FIRST);
foreach ($recursiveIterator as $key => $value) {
if (is_array($value) && array_key_exists('special_key', $value)) {
$replaced = array_fill(0, count($value), $value['special_key']);
$value = array_combine(array_keys($value), $replaced);
$value['new_key'] = 'new value';
$currentDepth = $recursiveIterator->getDepth();
for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--) {
$subIterator = $recursiveIterator->getSubIterator($subDepth);
$subIterator->offsetSet($subIterator->key(), ($subDepth === $currentDepth ? $value : $recursiveIterator->getSubIterator(($subDepth+1))->getArrayCopy()));
}
}
}
return $recursiveIterator->getArrayCopy();
$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'
]
]
];
?>
关键在于遍历回树的顶部以在该级别保存更改 - 仅仅调用 `$recursiveIterator->offsetSet();` 只会设置根数组上的键。