Question

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?

Était-ce utile?

La solution

array_walk_recursive($array, 'replaceMy');

function replaceMy(&$item) {
    str_replace('My', 'Your', $item);
}

Autres conseils

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']);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top