在非重复值上合并数组

时间:2018-11-01 13:23:16

标签: php arrays

说我有以下关联数组,如何将两者结合起来形成不重复的数组。我已经尝试过数组合并,但是它不起作用。对此的任何建议都将受到高度赞赏,数组唯一和数组组合不适用于本练习。 //数组A

Array
(
    [0] => Array
        (
            [data_month] => Jan
            [quantity] => 123
        )

    [1] => Array
        (
            [data_month] => Mar
            [quantity] => 286
        )
);

//阵列B

Array
(
    [0] => Array
        (
            [data_month] =>Jan
            [quantity] => 0
        )

    [1] => Array
        (
            [data_month] => Feb
            [quantity] => 0
        )

    [2] => Array
        (
            [data_month] => Mar
            [quantity] => 0
        )
[3] => Array
        (
            [data_month] => Apr
            [quantity] => 0
        )
[4] => Array
        (
            [data_month] => May
            [quantity] => 0
        )
);

//结果

Array
(
    [0] => Array
        (
            [data_month] => Jan
            [quantity] => 123
        )

    [1] => Array
        (
            [data_month] => Feb
            [quantity] => 0
        )

    [2] => Array
        (
            [data_month] => Mar
            [quantity] => 286
        )
[3] => Array
        (
            [data_month] => Apr
            [quantity] => 0
        )
[4] => Array
        (
            [data_month] => May
            [quantity] => 0
        )
);

1 个答案:

答案 0 :(得分:0)

这可能不是最有效的编码方式,但是如果您将data_month作为键,并将数量作为值分配给新数组,则可以检查该值是否存在,并添加数量(如果存在)。然后,您必须添加另一个循环以将其恢复为原始格式:

// loop through each array and assign it to a third, adding to the value if the key already exists
foreach($arr1 as $value) {
        if (isset($arr3[$value['data_month']])) {
                $arr3[$value['data_month']] = $arr3[$value['data_month']] + $value['quantity'];
        } else {
                $arr3[$value['data_month']] = $value['quantity'];
        }
}
foreach($arr2 as $value) {
        if (isset($arr3[$value['data_month']])) {
                $arr3[$value['data_month']] = $arr3[$value['data_month']] + $value['quantity'];
        } else {
                $arr3[$value['data_month']] = $value['quantity'];
        }
}

// use the key/value pairs to populate the final arrays
foreach($arr3 as $key => $value) {
        $final[] = array(
                'data_month' => $key,
                'quantity' => $value
        );
}