[英]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]);
}
}
PHP具有一个名为array_merge_recursive
的函数:
$c = array_merge_recursive($a, $b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.