phparraysmultidimensional-arraysumgrouping

Group rows of a 2d array and sum one column per group


I have an array in php like so:

[0] => Array
    (
        [cust_id] => 1006
        [no_of_subs] => 2
        [dlv_id] => 1000
    )

[1] => Array
    (
        [cust_id] => 1011
        [no_of_subs] => 3
        [dlv_id] => 1000
    )

[2] => Array
    (
        [cust_id] => 1012
        [no_of_subs] => 5
        [dlv_id] => 1001
    )

[3] => Array
    (
        [cust_id] => 1013
        [no_of_subs] => 6
        [dlv_id] => 1001
    )

I don't need the cust_id field. I just need to group the dlv_id and the sum of no_of_subs for each matching dlv_id. The result should look like this:

[0] => Array
    (
        [dlv_id] => 1000
        [no_of_subs] => 5
        
    )

[1] => Array
    (
        [cust_id] => 1011
        [no_of_subs] => 11
        
    )

Solution

  • The simplest, most efficient way to group and sum is to perform a single loop and assign temporary associative keys.

    When a row is identified as a new dlv_id row, save the two desired elements, otherwise add the no_of_subs value to the pre-existing value.

    Optionally, remove the temporary keys with array_values().

    Code (Demo)

    $array = [
        ["cust_id" => 1006, "no_of_subs" => 2, "dlv_id" => 1000],
        ["cust_id" => 1011, "no_of_subs" => 3, "dlv_id" => 1000],
        ["cust_id" => 1012, "no_of_subs" => 5, "dlv_id" => 1001],
        ["cust_id" => 1013, "no_of_subs" => 6, "dlv_id" => 1001]
    ];
    
    foreach ($array as $row) {
        if (!isset($result[$row["dlv_id"]])) {
            $result[$row["dlv_id"]] = ["dlv_id" => $row["dlv_id"], "no_of_subs" => $row["no_of_subs"]];
        } else {
            $result[$row["dlv_id"]]["no_of_subs"] += $row["no_of_subs"];
        }
    }
    var_export(array_values($result));
    

    Output:

    array (
      0 => 
      array (
        'dlv_id' => 1000,
        'no_of_subs' => 5,
      ),
      1 => 
      array (
        'dlv_id' => 1001,
        'no_of_subs' => 11,
      ),
    )