计算两个同名的数组项

Count two array items with same name as one

我有一个包含不同类型商品的多维数组,但是有重复的商品名称和数量,我想计算一个数组中每个产品的总数量。我尝试了一些解决方案,例如 if(in_array) 但没有成功! 我也尝试过推送 $array 中的每个项目但没有运气

Array
(
    [0] => Array
        (
            [product] => SUCRE 25 KG
            [quantity] => 20
        )
...
    [3] => Array
        (
            [product] => lait
            [quantity] => 20
        )
...
    [11] => Array
        (
            [product] => lait
            [quantity] => 6
        )

    [12] => Array
        (
            [product] => SUCRE 25 KG
            [quantity] => 4
        )

    [13] => Array
        (
            [product] => SUCRE 25 KG
            [quantity] => 4
        )

    [14] => Array
        (
            [product] => lait 
            [quantity] => 10
        )

    [15] => Array
        (
            [product] => SUCRE 25 KG
            [quantity] => 20
        )
...etc

)

我希望它像这样输出

Array
(
    [0] => Array
        (
            [product] => SUCRE 25 KG
            [quantity] => 48
        )
...

    [3] => Array
        (
            [product] => lait
            [quantity] => 36
        )
...etc

)

我的代码是这样的:

    $array = array();
    
    while($row = $result->fetch_assoc()){
        $v = json_decode($row['order_items'], true);
        foreach ($v as $key => $valuex) {
            foreach ($valuex as $key => $value) {
                array_push($array, array('product' => $value['productname'], 'quantity' => $value['quantity']));
            }
        }
    }
print_r($array);

我在 http://sandbox.onlinephpfunctions.com/code/9367d8f79b24ce0faca5c62a4e85127d39b92348

测试了这个
$array = array(array("product" => "sugar", "quantity" => 15),
    array("product" => "milk", "quantity" => 22),
    array("product" => "sugar", "quantity" => 3),
    array("product" => "milk", "quantity" => 1));

$counter = array();
$currentProduct;
foreach ($array as $innerArray){
    foreach ($innerArray as $key => $value) {
        if ($key == 'product') {
            $currentProduct = $value;
            continue;
        }
        
        if (!array_key_exists($currentProduct, $counter)) {
                $counter[$currentProduct] = 0;
            }
        
        $counter[$currentProduct] = $counter[$currentProduct] + intval($value);
    }
}

print_r($counter);

输出:

Array
(
    [sugar] => 18
    [milk] => 23
)