合并2个数组相同的键

时间:2016-08-05 13:43:28

标签: php arrays

我想在同一个键上合并两个数组。我尽我所能去做但却无法取得成功。我在下面添加了两个数组。请详细检查两个阵列,并帮助我如何使用相同的键合并它。

这是第一个阵列:

Array
(
    [1] => Array
        (
            [costprice1] => 500
            [margin1] => 20

        )

    [2] => Array
        (
            [costprice2] => 600
            [margin2] => 15

        )

    [3] => Array
        (
            [costprice3] => 700
            [margin3] => 25

        )

)

这是2阵列:

Array
(
    [1] => Array
        (

            [entityType1] => Products1
        )
    [2] => Array
        (
            [entityType2] => Products2
        )
    [3] => Array
        (
            [entityType3] => Products3
        )
)

我想要那个阵列,请建议我

Array
(
    [1] => Array
        (

            [entityType1] => Products1
            [costprice1] => 500
            [margin1] => 20
        )
    [2] => Array
        (
            [entityType2] => Products2
            [costprice2] => 600
            [margin2] => 15
        )
    [3] => Array
        (
            [entityType3] => Products3
            [costprice3] => 700
            [margin3] => 25
        )
)

请帮我如何合并两个数组

2 个答案:

答案 0 :(得分:1)

试试这个:

foreach($array1 as $key => $value) {
    $array1[$key]['entityType'.$key] = $array2[$key]['entityType'.$key];
}
print_r($array1);

答案 1 :(得分:0)

<?php

$array1 = [
  1 => [
    'costprice1' => 500,
    'margin1' => 20
  ],
  2 => [
    'costprice2' => 600,
    'margin2' => 15
  ],
  3 => [
    'costprice2' => 700,
    'margin2' => 25
  ],
];

$array2 = [
  1 => ['entityType1' => 'Products1'],
  2 => ['entityType2' => 'Products2'],
  3 => ['entityType3' => 'Products3'],
];

array_walk($array2, function(&$v, $k)use($array1){
    $v = array_merge($v, $array1[$k]);
});

print_r($array2);

输出:

Array
(
    [1] => Array
        (
            [entityType1] => Products1
            [costprice1] => 500
            [margin1] => 20
        )

    [2] => Array
        (
            [entityType2] => Products2
            [costprice2] => 600
            [margin2] => 15
        )

    [3] => Array
        (
            [entityType3] => Products3
            [costprice2] => 700
            [margin2] => 25
        )

)

https://eval.in/618561