I currently have an array of DateTimes representing date for events. I'm trying to find events that repeat weekly and group them together.
For example:
2014-01-27T00:00:00+01:00
2014-02-03T00:00:00+01:00
2014-02-10T00:00:00+01:00
2014-02-17T00:00:00+01:00
2014-04-28T00:00:00+02:00
2014-05-05T00:00:00+02:00
Would be split into:
2014-01-27T00:00:00+01:00
2014-02-03T00:00:00+01:00
2014-02-10T00:00:00+01:00
2014-02-17T00:00:00+01:00
2014-04-28T00:00:00+02:00
2014-05-05T00:00:00+02:00
I'm currently doing this by starting at the beginning of the array, then adding 7 days to the date, looping through the entire array to see if there is anything that matches. If a match is found I add that to a stack and repeat the process.
Is there a more simplistic way to approach this?
Actual code:
$dateGroups = array();
while(!empty($remainingDates)) {
// Get the first item
$startDate = array_shift($remainingDates);
$currentDate = $startDate;
$repeatCount = 1;
foreach($remainingDates as $key => $date) {
$interval = $currentDate->diff($date);
if($interval->d == 7) {
unset($remainingDates[$key]);
$repeatCount++;
$currentDate = clone $date;
}
}
$endDate = $currentDate;
$dateGroups[] = array('start' => $startDate, 'end' => $endDate, 'occurrences' => $repeatCount);
}