I have array like this
Array
(
[0] => Array
(
[0] => 2023-06-28
[1] => 5482
)
[1] => Array
(
[0] => 2023-06-28
[1] => 316
)
[2] => Array
(
[0] => 2023-06-28
[1] => 189
)
[3] => Array
(
[0] => 2023-06-29
[1] => 5
)
[4] => Array
(
[0] => 2023-06-29
[1] => 0
)
[5] => Array
(
[0] => 2023-06-30
[1] => 5788
)
[6] => Array
(
[0] => 2023-06-30
[1] => 1266
)
)
I want to group them by date and sum value
$output=array();
foreach($array as $values){
$date = $values[0];
$output[$d][1]+=$values[1];
}
The $output result is
Array
(
[0] => Array
(
[0] => 2023-06-28
[1] => 5987
)
[1] => Array
(
[0] => 2023-06-29
[1] => 5
)
[2] => Array
(
[0] => 2023-06-30
[1] => 7054
)
)
All this is ok but i need instead of SUM value to calculate average, so my idea was to get SUM of same day in foreach and than divide the sum by the total number or same day count. Example for date 2023-06-28 SUM is 5987 and count is 3 so result should be 5987 / 3.
Any idea how i can do that, or maybe other idea hot to get average in foreach ?
>Solution :
# Build the array
$output = [];
foreach($array as $values){
$date = $values[0];
if(!isset($output[$date])) {
$output[$d] = ['total' => 0, 'count' => 0];
}
$output[$date]['total'] += $values[1];
$output[$date]['count']++;
}
# Calculate the sums
foreach($output as $date => $data){
$output[$date]['average'] = ($data['total'] / $data['count'];
}
print_r($output);