Question

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);

    }
Was it helpful?

Solution

check out this function in php http://www.php.net/manual/en/datetime.diff.php

it gives you the difference between two dates, you can scan other dates, find 7 day differences (or get $diff->d%7==0) and group by that..

eventually, pre-sort into tables of groups using %7==0 and then check those groups for integrity if you need only dates that happen EVERY week. should speed up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top