以特殊方式合并数组

时间:2014-04-30 12:56:53

标签: php arrays

我正在寻找使用另一个数组操作数组的最佳方法。

我的第一个数组看起来像这样(对于某个布局):

$layout = array(
    'title' => 'The default Title',
    'meta' => array(
        'keywords' => '<meta name="keywords" content="key1, key2">',
        'description' => '<meta name="description" content="Here description">'
    )
);

我的第二个数组看起来像这样(对于某个视图)

$view = array(
    'title' => 'Home',
    'meta' => array(
        'description' => '<meta name="description" content="This is the Home">',
        'charset' => '<meta charset="utf-8">'
    )
);

我希望以某种方式合并这些数组,我将获取第一个数组并更改或添加第二个数组中的条目。在第一个数组中都是默认值。在第二个是变化或更精确的事情。

最后我想要这个:

$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">'
    )
);

我用array_merge尝试过它。但这不起作用,因为我还有数字数组,这不起作用。将添加数字数组,而不仅仅是替换。

1 个答案:

答案 0 :(得分:1)

尝试使用array_replace_recursive功能:

$final = array_replace_recursive($layout, $view);

结果:

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">
        )

)
相关问题