Finding overlaping date ranges in an array
I have an array of date ranges like this:
[0] => Array
(
[start_time] => 2011-10-01 00:00:00
[end_time] => 2011-10-05 00:00:00
[name] => Apples
)
[1] => Array
(
[start_time] => 2011-10-04 00:00:00
[end_time] => 2011-10-10 00:23:00
[name] => Oranges
)
[2] => Array
(
[start_time] => 2011-10-15 00:00:00
[end_time] => 2011-10-20 00:23:00
[name] => Bananas
)
I'm trying to calculate the overlap between each event and 'split' this overlap into a separate item in the array, then adjust the start_time and end_time of the intersecting events accordingly, so they no longer overlap. For example, in the array above 'Apples' intersects with Oranges by one day, so I'd like to end up with an array that looks like this.
[0] => Array
(
[start_time] => 2011-10-01 00:00:00
[end_time] => 2011-10-04 00:00:00
[name] => Apples
)
[1] => Array
(
[start_time] => 2011-10-04 00:00:00
[end_time] => 2011-10-05 00:00:00
[name] => Apples Oranges
)
[2] => Array
(
[start_time] => 2011-10-05 00:00:00
[end_time] => 2011-10-10 00:23:00
[name] =&g开发者_Python百科t; Oranges
)
[3] => Array
(
[start_time] => 2011-10-15 00:00:00
[end_time] => 2011-10-20 00:23:00
[name] => Bananas
)
To get reasonably efficient code, I guess that you will have to order the dates by beginning time. After that, it should be fairly easy to get the intersections by walking over the end-dates.
As you said that you were new to PHP, you might want to read up on the function http://php.net/manual/en/function.strtotime.php This converts your formatted dates into unix timestamps, thus making them comparable.
For sorting your above data structure, have a look at the different sorting functions for arrays: http://de3.php.net/manual/en/array.sorting.php
Especially uasort
might be interesting for you.
As the others said, SO is not here to write your code, so have a look at set theory to get an idea for even better performing solutions.
精彩评论