Search code examples
phparrayssum

Group array values based on key and count quantity of grouped products in php


Maybe someone has already asked, but I didn't find the right answer. I need group arrays by mpn and product_id key values and count it's quantities. my array:

    [0] => Array
        (
            [product] => Product HTC
            [mpn] => 
            [quantity] => 3
            [product_id] => 28
        )

    [1] => Array
        (
            [product] => Product HTC
            [mpn] => ggg
            [quantity] => 5
            [product_id] => 28
        )

    [2] => Array
        (
            [product] => Product HTC
            [mpn] => ggg
            [quantity] => 1
            [product_id] => 28
        )

    [3] => Array
        (
            [product] => Product HTC
            [mpn] => ggg
            [quantity] => 1
            [product_id] => 28
        )

    [4] => Array
        (
            [product] => Product HTC
            [mpn] => fff
            [quantity] => 1
            [product_id] => 28
        )

the desired result:

[0] => Array
    (
        [product] => Product HTC
        [mpn] => 
        [quantity] => 3
        [product_id] => 28
    )

[1] => Array
    (
        [product] => Product HTC
        [mpn] => ggg
        [quantity] => 7
        [product_id] => 28
    )


[2] => Array
    (
        [product] => Product HTC
        [mpn] => fff
        [quantity] => 1
        [product_id] => 28
    )

I have tried this suggestion Group array values based on key in php? but no success.


Solution

  • With this code you can obtain an array group by mpn. With $myList is your original array.

    // For Each Element
    foreach ($myList as $myKey => $myValue)
    {
        // Define New Key
        $newKey = $myValue["mpn"];
    
        // You can Define New Key with Concatenation of Multiple Element
        // Ex : $newKey = $myValue["mpn"]."_".$myValue["product_id"];
    
        // If Never Memorised OR Already Memorised
        if(!array_key_exists($newKey,$newList)) $newList["$newKey"] = $myValue;
        else $newList["$newKey"]["quantity"] = bcadd($newList["$newKey"]["quantity"],$myValue["quantity"],0);
    }
    // End - For Each Element
    
    // Display Result
    echo "<pre>"; print_r($newList); echo "</pre>";