Search code examples
phparraysmultidimensional-arraysumgrouping

Group rows by column value and within groups create new sum column and count column


I am trying to summarize a php multidimensional, I have an array structure like this;

Array
(
    [0] => Array
        (
            [product_id] => 1
            [product_name] => Product1
            [product_price] => 0.90
        )

    [1] => Array
        (
            [product_id] => 2
            [product_name] => Product2
            [product_price] => 1.50
        )

    [2] => Array
        (
            [product_id] => 1
            [product_name] => Product1
            [product_price] => 0.90
        )

)

I would like to write a function that could easily summarize any duplicate entries and return a new array like this (essentially tallying up the product_price and creating a product_qty field);

Array
(
    [0] => Array
        (
            [product_id] => 1
            [product_name] => Product1
            [product_price] => 1.80
            [product_qty] => 2
        )

    [1] => Array
        (
            [product_id] => 2
            [product_name] => Product2
            [product_price] => 1.5
            [product_qty] => 1
        )

)

I have tried using array_sum(), array_merge() and array_map() but none are returning the above desired result.


Solution

  • Here's some simple code:

    $summary = array();
    foreach ($products as $product) {
        if (!isset($summary[$product['product_id']])) {
            $summary[$product['product_id']] = array_merge(
                $product, array('product_qty' => 1));
        } else {
            $summary[$product['product_id']]['product_price'] += $product['product_price'];
            $summary[$product['product_id']]['product_qty']++;
        }
    }