简体   繁体   中英

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:

$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. 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.

Use looping with isset() function. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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