简体   繁体   English

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

[英]How can I add a value to an array's key from another array with the same key in PHP?

I have the following 2 arrays: 我有以下2个数组:

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

I would like for $b to "adopt" $a 's values, but not the other way around. 我希望$b能够“采用” $a的值,但不能反过来。 My final array would look like: 我的最终数组如下所示:

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

How can I achieve this? 我该如何实现? I've tried multiple methods but none seem to array_merge correctly. 我尝试了多种方法,但似乎都没有正确地array_merge

Use looping with isset() function. isset()函数一起使用循环。 More details in code comments below: 以下代码注释中的更多详细信息:

// 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 雷斯特演示

PHP具有一个名为array_merge_recursive的函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM