Find matching date ranges in an array

I have an array of date ranges, for example:

[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 try to calculate the overlap between each event and “split” this overlap into a separate element in the array, and then change the start and end times of the intersecting events accordingly so that they no longer overlap. For example, in the array above, “Apples” intersect with oranges for one day, so I would like to get 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] => Oranges ) [3] => Array ( [start_time] => 2011-10-15 00:00:00 [end_time] => 2011-10-20 00:23:00 [name] => Bananas ) 
+4
source share
1 answer

To get a reasonably efficient code, I assume that you have to order dates by start time. After that, it should be pretty easy to get crossroads by going through the end dates.

As you said that you are new to PHP, you can read the function http://php.net/manual/en/function.strtotime.php This converts your formatted dates to unix, which makes them comparable.

To sort the above data structure, look at the various sorting functions for arrays: http://de3.php.net/manual/en/array.sorting.php

Especially interesting for you is uasort .

As others have said, SO is not here to write your code, so take a look at set theory to get an idea of ​​even more efficient solutions.

0
source

All Articles