你可以不使用循环,而是使用 json_encode()
方法将数组转换为字符串,然后进行字符串替换,最后再使用 json_decode()
将其转换回数组:
function replaceKey($array, $old, $new)
{
$str = json_encode($array);
$str = str_replace('"'.$old.'":','"'.$new.'":',$str);
return json_decode($str, TRUE);
}
现在这个方法并不会检查与已有键的冲突(可以很容易地添加字符串比较检查),而且对于大型数组中的单个替换可能不是最佳解决方案。但是将数组展平为字符串进行替换的好处在于,它有效地使替换递归,因为任何深度的匹配都可以在一次替换中全部替换:
$arr = array(
array(
'name' => 'Steve'
,'city' => 'Los Angeles'
,'state' => 'CA'
,'country' => 'USA'
,'mother' => array(
'name' => 'Jessica'
,'city' => 'San Diego'
,'state' => 'CA'
,'country' => 'USA'
)
)
,array(
'name' => 'Sara'
,'city' => 'Seattle'
,'state' => 'WA'
,'country' => 'USA'
,'father' => array(
'name' => 'Eric'
,'city' => 'Atlanta'
,'state' => 'GA'
,'country' => 'USA'
,'mother' => array(
'name' => 'Sharon'
,'city' => 'Portland'
,'state' => 'OR'
,'country' => 'USA'
)
)
)
);
$replaced = replaceKey($arr,'city','town');
print_r($replaced);
输出
Array
(
[0] => Array
(
[name] => Steve
[town] => Los Angeles
[state] => CA
[country] => USA
[mother] => Array
(
[name] => Jessica
[town] => San Diego
[state] => CA
[country] => USA
)
)
[1] => Array
(
[name] => Sara
[town] => Seattle
[state] => WA
[country] => USA
[father] => Array
(
[name] => Eric
[town] => Atlanta
[state] => GA
[country] => USA
[mother] => Array
(
[name] => Sharon
[town] => Portland
[state] => OR
[country] => USA
)
)
)
)
true
作为array_search()
的第三个参数传递进去即可;完成了 :) - Ja͢ck