我有以下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
都不正确。
答案 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]);
}
}
答案 1 :(得分:2)
PHP具有一个名为array_merge_recursive
的功能:
$c = array_merge_recursive($a, $b);