我们说我有一个这样的数组:
$myArray = array(
'a' => 'alpha',
'b' => array(
'Z' => 'zulu' )
);
我想搜索关键字' Z'并取代它的价值。
我尝试过迭代器,foreach循环等,但没有运气。
* 修改后的语法。
答案 0 :(得分:1)
<?php
$myArray = array(
'a' => 'alpha',
'b' => array (
'Z' => 'zulu'
),
);
foreach($myArray as $key => $value) {
if (is_array($value)) {
foreach($value as $k => $v) {
if ($k == 'Z')
{
//do something
$myArray[$key]['newKey'] = $v;
unset($myArray[$key][$k]);
}
}
}
}
print_r($myArray);
输出:
Array
(
[a] => alpha
[b] => Array
(
[newKey] => zulu
)
)
答案 1 :(得分:1)
您可以使用array_walk_recursive
并通过引用传递:
array_walk_recursive($myArray, function(&$item, $key) {
if ($key == 'Z') $item = "hi";
});
http://sandbox.onlinephpfunctions.com/code/ad750cbb5b30b87f9e6068ba15420cf924ed5a7b
答案 2 :(得分:1)
您可以传递对array_walk_recursive的引用:
$myArray = array(
'a' => 'alpha',
'b' => array(
'Z' => 'zulu' )
);
$newvalue = 'zebra';
array_walk_recursive($myArray, function(&$value, $key) use($newvalue){
if($key=='Z'){
$value = $newvalue;
}
});
print_r($myArray);