我想以递归方式更新下面的数组,用一些其他值替换包含[myKey]键的数组的内容(假设[foo] => bar,[bar] => foo)。这没有使用引用,因为我已经有一些代码工作,但我想重构它。
Array
(
[objects] => Array
(
[0] => Array
(
[somekey] => value
[items] => Array
(
[0] => Array
(
[myKey] => item1
)
[1] => Array
(
[myKey] => item2
)
)
)
[1] => Array
(
[otherKey] => other value
[items] => Array
(
[0] => Array
(
[myKey] => item3
)
[1] => Array
(
[myKey] => item4
)
)
)
[2] => Array
(
[myKey] => item5
)
)
)
我最终想要的是下面的内容。不要考虑我将如何决定使用哪些键/值,以及如何将它们添加到数组......
Array
(
[objects] => Array
(
[0] => Array
(
[somekey] => value
[items] => Array
(
[0] => Array
(
[foo] => bar
)
[1] => Array
(
[bar] => foo
)
)
)
[1] => Array
(
[otherKey] => other value
[items] => Array
(
[0] => Array
(
[whatever] => value
)
[1] => Array
(
[foo1] => bar
)
)
)
[2] => Array
(
[bar1] => foo2
)
)
)
提前致谢!
答案 0 :(得分:1)
您可以尝试此功能:
function replace_recursive_array($array, $old_key, $new_key, $new_value) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = replace_recursive_array($value, $old_key, $new_key, $new_value);
}elseif($key == $old_key) {
$array[$new_key] = $new_value;
}
}
unset($array[$old_key]);
return $array;
}