Set one:
- 2014-04-05 To 2014-06-27
- 2014-06-28 To 2014-10-19
Set two:
- 2014-04-05 To 2014-05-02
- 2014-05-03 To 2014-05-31
- 2014-06-01 To 2014-10-19
What I need this to output is:
- 2014-04-05 To 2014-05-02
- 2014-05-03 To 2014-05-31
- 2014-06-01 To 2014-06-27
- 2014-06-28 To 2014-10-19
I attempted to use a function to check for overlaps as such:
!($lhs['RecordOnset'] > $rhs['RecordOffset'] || $lhs['RecordOffset'] < $rhs['RecordOnset'])
And used a for loop to check for the overlap:
for($i = 1; $i < sizeof($arr1); $i++) {
for($j = 1; $j < sizeof($arr2); $j++) {
$record = $arr1[$i];
if($result = $this->intersects($arr1[$i], $arr2[$j])) {
// $result;
}
}
}
The issue that I'm having is when I break a date range out, it doesn't check the new range that was created when looping. I do not have the ability to use SQL with this so I must come up with a programmatic solution. I've tried several different methods including some foreach loops.
The data is received in a date format as show in an array like such:
$arr1 = array(array('start'=>'04/05/2014', 'end'=> '2014-06-27'), array('start'=>'2014-06-28', 'end'=> '2014-10-19'));
$arr2 = array(array('start'=>'04/05/2014', 'end'=> '2014-05-02'), array('start'=>'2014-05-03', 'end'=> '2014-05-31'),array('start'=>'2014-06-01', 'end'=> '2014-10-19'));
The second pair would be a separate array, since it may have the same keys.
Any guidance or help with this is greatly appreciated. Date ranges with PHP has very limited resource online.
Usage :
$output = mergeRanges($input);
This method is originally designed to merge any kind on numeric ranges, timestamps included and supports any kind of overlaps. It takes an array of objects in input, containing "from" and "to" keys which is customizable.
Example :
Result :
Preparing
output
Ok. Now we need loop array
$starts
: for eachstart
find closestend
that more thenstart
. Do it:output:
What you need.
Note About this line in loops:
We can have this situation:
But it's wrong. Need only last range
2014-04-05 To 2014-05-02
. And line:override value with same key=> finally will be set proper
2014-04-05
to key2014-05-02
.Here is my solution: