phparraysmultidimensional-arraysumarray-column

Group 2d array in batches of 10 rows then sum the values in each batch


I have an array of rows which need to be batched into groups of ten rows then their values summed.

Sample array with 13 rows:

[
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
    ['amount_paid' => 2050.00],
]

Desired result from sample array:

[20500.0, 8200.0]

The above represents the sum of the first 10 rows, then the sum of the remaining 3 rows.

What I tried is only for first 10 and I can't think of how to handle the data for every 10 with dynamic number of rows.

for ($i = 0; $i < count($json); $i++) {
    if ($i < 10) {
        $subtotalamount += floatval($json[$i]['amount_paid']);
    }
}

Solution

  • Short solution with range, array_slice and array_column functions:

    // $arr is your initial array
    $sub_totals = [];
    foreach(range(0, count($arr), 10) as $k){
        $sub_totals[] = array_sum(array_column(array_slice($arr, $k, 10), 'amount_paid'));
    }