2

我想将两个数组合并为一个数组,如下所示,

阵列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
        )

)

数组2:

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
        )

)

如何将这些数组元素合并为一个数组元素?

4

6 回答 6

9
foreach ($origArray as $key => &$subArray)
    $subArray += $arrayToBeAdded[$key];

$origArray您要合并到的数组和要合并到的数组在哪里$arrayToBeAdded

于 2013-04-27T12:17:30.043 回答
1

用户array_merge_recursive()

$final = array_merge_recursive($array1, $array2);
于 2013-04-27T12:19:58.587 回答
0

试试这个鲜为人知的+数组运算符重载:

$result = $array1[0] + $array2[0]
于 2013-04-27T12:20:07.647 回答
0

对于这个 php 有多种功能。您可以使用 $arrays = array_combine($array1, $array2);。

PHP.net - array_combine

希望它有所帮助!

于 2013-04-27T12:23:42.777 回答
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);
于 2013-04-27T12:28:48.927 回答
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 )
于 2013-04-27T12:31:02.720 回答