search

Home  >  Q&A  >  body text

In foreach loop in PHP, group by date and get count sum of same rows

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粉304704653P粉304704653424 days ago561

reply all(1)I'll reply

  • P粉807239416

    P粉8072394162023-09-17 16:01:12

    # 构建数组
    $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);

    reply
    0
  • Cancelreply