In foreach loop in PHP, group by date and get count sum of same rows
P粉304704653
P粉304704653 2023-09-16 19:05:48
0
1
485

I have an 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 by date and sum the values

$output=array(); foreach($array as $values){ $date = $values[0]; $output[$d][1]+=$values[1]; }
The result of

$output 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 ) )

This is all fine, but I need to calculate the average, not sum the values, so my idea is to get the sum of the same day in a foreach and then divide the sum by the amount of the same day. For example, for the date 2023-06-28, the sum is 5987 and the quantity is 3, so the result should be 5987/3.

Is there a way to do this, or some other way to get the average in a foreach?

P粉304704653
P粉304704653

reply all (1)
P粉807239416
# 构建数组 $output = []; foreach($array as $values){ $date = $values[0]; if(!isset($output[$date])) { $output[$date] = ['total' => 0, 'count' => 0]; } $output[$date]['total'] += $values[1]; $output[$date]['count']++; } # 计算总和 foreach($output as $date => $data){ $output[$date]['average'] = ($data['total'] / $data['count']); } print_r($output);
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!