Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group by date, sum value and get count of same row in foreach php

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading