我想将两个数组合并为一个数组,如下所示,
数组1:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
)
)
Array2:
Array
(
[0] => Array
(
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
预期的数组结果是:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
如何将这些数组元素合并为一个数组元素?
答案 0 :(得分:9)
foreach ($origArray as $key => &$subArray)
$subArray += $arrayToBeAdded[$key];
其中$origArray
是要合并到的数组,$arrayToBeAdded
是要合并的数组。
答案 1 :(得分:1)
用户array_merge_recursive()
:
$final = array_merge_recursive($array1, $array2);
答案 2 :(得分:0)
尝试数组的+
运算符的这个鲜为人知的重载:
$result = $array1[0] + $array2[0]
答案 3 :(得分:0)
答案 4 :(得分:0)
使用函数array_merge($array1[0], $array2[0])
。以下是相同
$array1 = array(0=>array('1'=>1,'2'=>2,'3'=>3));
$array2 = array(0=>array('4'=>4,'5'=>5,'6'=>6));
$result[0] = array_merge($array1[0],$array2[0]);
echo '<pre>';
print_r($result);
答案 5 :(得分:0)
由于你有唯一的密钥,你可以使用像+
运算符(联合)这样简单的东西......
例如:
$arr1 = [1=>'testing',2=>'stack',3=>'overflow'];
$arr2 = [4=>'something',5=>'else',6=>'here'];
$arr3 = $arr1 + $arr2;
print_r($arr3);
Results:
Array ( [1] => testing [2] => stack [3] => overflow [4] => something [5] => else [6] => here )