str_replace with subject as associative array
题
I have an haystack that's an associative array:
$array['header']['title'] = 'MyTitle';
$array['header']['subtitle'] = 'MySubtitle';
$array['body'] = 'MyBody';
I'd wish to replace every occurrence of 'My' with 'Your'.
I'm trying something like this:
$new_array = str_replace('My', 'Your', $array);
Sadly it works only on the first level (ie body
key).
Is there anything wrong? Is there a workaround?
解决方案
array_walk_recursive($array, 'replaceMy');
function replaceMy(&$item) {
str_replace('My', 'Your', $item);
}
其他提示
Try this one: array_walk_recursive
If your associative array is unknown, you will have to use a recursive method to go through it and do your replace if the value is a string.
Otherwise, use more calls:
$new_array = str_replace('My', 'Your', $array);
$new_array = str_replace('My', 'Your', $array['header']);
不隶属于 StackOverflow