phparraysmultidimensional-arraygroupingcounting

Group rows of a 2d array by year-month value of date column and count occurrences in each group


So I have this code:

$avaDates = [
    ['date_starts' => '2024-03-01'],
    ['date_starts' => '2024-03-09'],
    ['date_starts' => '2024-04-05'],
    ['date_starts' => '2024-04-09'],
    ['date_starts' => '2024-04-15'],
    ['date_starts' => '2024-05-03']
];
$sum = 0;
$months = '';
foreach ($avaDates as $date) {
    $monthCheck = substr($date['date_starts'], 0, -3);
    if ($months !== $monthCheck) {
        $months = $monthCheck;
        $dateFormat = date("F-Y", strtotime($months));

        echo strtolower($dateFormat) . ' ' . $sum . "\n";

        $sum = 0;
    }
    $sum++;
}

the actual output is this:

march-2024 0
april-2024 2
may-2024 3

I'm looking for this output:

march-2024 2
april-2024 3
may-2024 1

I can't seem to make the logic work. Here is a link to the sandbox to run my example: https://onlinephp.io/c/47724


Solution

  • You need to do group and count and you can do something like this to get:

    $avaDates = [['date_starts'=>'2024-03-01'],['date_starts'=>'2024-03-09'],['date_starts'=>'2024-04-05'],['date_starts'=>'2024-04-09'],['date_starts'=>'2024-04-15'],['date_starts'=>'2024-05-03']];
    
    $groupDates = array_reduce($avaDates, function ($months, $date) {
        $dateFormat = date("F-Y", strtotime($date['date_starts']));
        if (isset($months[$dateFormat])) {
            $months[$dateFormat]++;
        } else {
            $months[$dateFormat] = 1;
        }
        return $months;
    });
    print_r($groupDates);
    

    The array reduce function allows you to iterate through an array and group at the same time and return a value and, in this case, a new array with group by month and its count.

    to print the array you can do it by:

    foreach ($groupDates as $month => $count ) {
     echo $month . '->' . $count . "\n";
    }
    

    You can find the code here: https://onlinephp.io/c/47724