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
what im looking for is this output:
march-2024 2
april-2024 3
may-2024 1
cant seem to make the logic work, any help will be appreciated, here is a link to sandbox to run my example: https://onlinephp.io/c/47724
3
Answers
I think you can use
array_count_values
to ge the counts if you trim off the day value. Something like:should do it. May even be able to use
array_map
to shorten that.You need to do group and count and you can do something like this to get:
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:
You can find the code here: https://onlinephp.io/c/47724
print_month_sum()
).$months
with$monthCheck
and add1
to the sum (if it’s time to print).1
to a sum before printing if the month didn’t change.But it would be safer to use an array functions as suggested in other answers.