比较两个多维数组并添加缺失

时间:2021-08-04 12:19:46

I have two arrays which product IDs storing as keys.

我有两个数组,产品ID存储为键。

First array goes like :

第一个数组如下:

Array
(
    [1] => Array
    (
        [_sku] => 
        [_qty] => 1
    )
    [34] => Array
    (
        [_sku] => 
        [_qty] => 3
    )
    [23] => Array
    (
        [_sku] => 
        [_qty] => 1
    )
)

Second array goes like :

第二个数组如下:

Array
(
    [1] => Array
    (
        [_sku] => 
        [_qty] => 1
    )
    [54] => Array
    (
        [_sku] => 
        [_qty] => 1
    )
)

My first array is the logged in user's basket. Second is the same user's not logged in basket. When user logged in I have to compere these 2 arrays and add the missing keys to first array but if the same keys exists in two arrays I have to roundup the first array's _qty with second's _qty (like : [1] => _qty is 1 and second array has also 1 qty so make firsts qty = 2 ). or process what I want and create a third array also possible I guess.

我的第一个数组是登录用户的篮子。第二个是同一个用户没有登录篮子。当用户登录时,我必须主持这两个数组,并将缺少的键添加到第一个数组,但如果两个数组中存在相同的键,我必须用第二个_qty对第一个数组的_qty进行四舍五入(如:[1] => _qty为1第二个数组也有1个数量,所以第一个数字= 2)。或者我可以处理我想要的并创建第三个数组。

How to achive this?

如何实现这一目标?

1 个解决方案

#1


1  

A simple foreach should do the trick:

一个简单的foreach应该做的伎俩:

foreach ($second as $key => $value) {
    if (isset($first[$key])) {
        $first[$key]['_qty'] += $value['_qty'];
    } else {
        $first[$key] = $value;
    }
}

#1


1  

A simple foreach should do the trick:

一个简单的foreach应该做的伎俩:

foreach ($second as $key => $value) {
    if (isset($first[$key])) {
        $first[$key]['_qty'] += $value['_qty'];
    } else {
        $first[$key] = $value;
    }
}