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']);
}
}
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'));
}
range(0, count($arr), 10)
- generate an array containing a range of elements. It would be as [0, 10, 20]
. Those elements are boundaries for each 10-sized sequence
array_slice($arr, $k, 10)
- each next boundary $k
is used for extracting next 10-sized sequence/slice from the initial array $arr