Below is a snippet that uses array_reduce() to calculate totals from a detailed dataset. The data shown is representative of a larger dataset.
This code outputs the expected results. I'm seeking some peer input on how this array_reduce() is written because this is my first time using it in PHP. I'm more familiar with JavaScript .reduce() function. Is there a more concise way to write this?
<?php
$data = [
'header' => [
'customerId' => 28449,
'locationId' => 1278,
'orderId' => 764,
'orderDate' => '2022-02-01'
],
'detail' => [
'0' => [
'itemId' => 210711,
'orderQuantity' => 10,
'fillQuantity' => 8,
'unitPrice' => 120.54
],
'1' => [
'itemId' => 582284,
'orderQuantity' => 151,
'fillQuantity' => 144,
'unitPrice' => 85.68
],
'2' => [
'itemId' => 476537,
'orderQuantity' => 87,
'fillQuantity' => 87,
'unitPrice' => 25.75
]
]
];
$initialValues = array_fill_keys(['itemCount', 'orderQuantity', 'fillQuantity'], 0);
$totals = [];
$totals = array_reduce($data['detail'], function ($result, $item) {
$result['itemCount']++;
$result['orderQuantity'] += $item['orderQuantity'];
$result['fillQuantity'] += $item['fillQuantity'];
return $result;
}, $initialValues);
echo '<pre>' . print_r(['data' => $data, 'totals' => $totals], 1) . '</pre>';
?>
Here is the 'totals' output, which is correct:
[totals] => Array
(
[itemCount] => 3
[orderQuantity] => 248
[fillQuantity] => 239
)