首页 > 解决方案 > 如何将两个不同的数组合并到一个上

问题描述

如果您已经有相同的 ID,或者如果您没有创建新对象,如何更新对象数组、添加数量。

我试图在代码中解释数组以及我希望结果如何的想法。

旧数组

$a1 = [
    array(
        "id" => 1,
        "qty" => 1
    ),
    array(
        "id" => 2,
        "qty" => 1
    )
];

$a2 = [
    array(
        "id" => 1,
        "qty" => 1
    )
];

$output = array_merge($a1, $a2);

echo '<pre>';
print_r($output);
echo '</pre>';

结果错误:

Array
(
    [0] => Array
        (
            [id] => 1
            [qty] => 1
        )

    [1] => Array
        (
            [id] => 2
            [qty] => 1
        )

    [2] => Array
        (
            [id] => 1
            [qty] => 1
        )

)

我需要什么,除了如果ID不包含,添加。

Array
(
    [0] => Array
        (
            [id] => 1
            [qty] => 2
        )

    [1] => Array
        (
            [id] => 2
            [qty] => 1
        )   
)

标签: php

解决方案


您可以将第一个数组作为基础,然后搜索productid. 然后添加数量并重新计算价格,或者您只需添加重新格式化的元素(id转换product)。

$result = $a;
foreach($b as $element) {
    $matchingProductIndex = array_search($element['id'], array_column($a, 'product'));
    if ($matchingProductIndex !== false) {
        $pricePerUnit = $result[$matchingProductIndex]['price'] / $result[$matchingProductIndex]['qty'];
        $result[$matchingProductIndex]['qty'] += $element['qty'];
        $result[$matchingProductIndex]['price'] = $result[$matchingProductIndex]['qty'] * $pricePerUnit;
    } else {
        $result[] = [
            'qty' => $element['qty'],
            'product' => $element['id'],
            'price' => $element['price'],
        ];
    }
}

print_r($result);

工作示例


推荐阅读