如何从PHP中具有相同键的另一个数组向数组的键添加值?

时间:2018-10-08 17:39:39

标签: php arrays

我有以下2个数组:

$a = [ 'post_type' => 'ese' ];
$b = [ 'demo_handle' => 'demo-3', 'post_type' => [ 'aaa', 'bbb' ], 'id' => 3'];

我希望$b“采用” $a的值,但不能反过来。我的最终数组如下:

$c = [ ..., 'post_type' => [ 'aaa, 'bbb', 'ese'], ...];

我该如何实现?我尝试了多种方法,但似乎array_merge都不正确。

2 个答案:

答案 0 :(得分:2)

使用isset()函数进行循环。以下代码注释中的更多详细信息:

// Loop over the $b array
foreach ($b as $key => $value) {

    // Check if this key exists in $a array also
    if (isset($a[$key])) {

        // if exists, we can merge them 
        // We need to typecast value in $a to array 
        // since, array_merge requires array arguments
        $b[$key] = array_merge((array)$value, 
                               (array)$a[$key]);
    }
}

Rextester DEMO

答案 1 :(得分:2)

PHP具有一个名为array_merge_recursive的功能:

$c = array_merge_recursive($a, $b);