Reputation: 308
I'm looking for the best way to manipulate an array with another array.
My first array looks something like this (for a certain layout):
$layout = array(
'title' => 'The default Title',
'meta' => array(
'keywords' => '<meta name="keywords" content="key1, key2">',
'description' => '<meta name="description" content="Here description">'
)
);
My second array looks something like this (for a certain view)
$view = array(
'title' => 'Home',
'meta' => array(
'description' => '<meta name="description" content="This is the Home">',
'charset' => '<meta charset="utf-8">'
)
);
I want to merge this arrays in a way, that i take the first array and change or add the entries from the second array. In the first array are all default values. In the second are changes or more precise thing.
At the end I want to have this:
$final = array(
'title' => 'Home',
'meta' => array(
'keywords' => '<meta name="keywords" content="key1, key2">',
'description' => '<meta name="description" content="This is the Home">',
'charset' => '<meta charset="utf-8">'
)
);
I tried it with array_merge. But this does not work, because I have also numeric arrays where this does not work. Numeric arrays will be added, not only replaced.
Upvotes: 1
Views: 43
Reputation: 149040
Try using the array_replace_recursive
function:
$final = array_replace_recursive($layout, $view);
Results in:
Array
(
[title] => Home
[meta] => Array
(
[keywords] => <meta name="keywords" content="key1, key2">
[description] => <meta name="description" content="This is the Home">
[charset] => <meta charset="utf-8">
)
)
Upvotes: 1