Search code examples
phparraysjsonarray-push

Count two array items with same name as one


I have multidimensionnel array with different types of items but there are repeated items by name with quantity, I want to count each product total quantity in one array. I have tried some solutions like if(in_array) but no luck !. I also have tried pushing every item in $array and no luck

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

)

and I want it to output like this

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

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

)

I have my code like this:

    $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);

Solution

  • I tested this at 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);
    

    Output:

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