I have some date ranges in array, and want to merge them. The result is a date range with the lowest start date and the highest end date. These are some samples in different cases. case 1:
$case1 = array(
array(
'start_date' => '2014-10-06',
'end_date' => '2014-10-23',
),
array(
'start_date' => '2014-10-10',
'end_date' => '2014-10-12',
),
array(
'start_date' => '2014-10-17',
'end_date' => '2014-10-19',
),
);
//expected
$res1 = array('start_date' => '2014-10-06', 'end_date' => '2014-10-23');
case 2:
$case2 = array(
array(
'start_date' => '2014-10-06',
'end_date' => '2014-10-23',
),
array(
'start_date' => '2014-09-10',
'end_date' => '2014-10-12',
),
array(
'start_date' => '2014-10-17',
'end_date' => '2014-10-19',
),
);
//expected
$res2 = array('start_date' => '2014-09-10', 'end_date' => '2014-10-23');
case 3:
$case3 = array(
array(
'start_date' => '2014-10-06',
'end_date' => '2014-10-23',
),
array(
'start_date' => '2014-10-10',
'end_date' => '2014-10-12',
),
array(
'start_date' => '2014-10-17',
'end_date' => '2014-11-12',
),
);
//expected
$res3 = array('start_date' => '2014-10-06', 'end_date' => '2014-11-12');
Your help is highly appreciated. Thank you guys
Since you're just aiming at the lowest and highest date, just convert them to seconds, sort them then get the first and last:
$case1 = array(
array(
'start_date' => '2014-10-06',
'end_date' => '2014-10-23',
),
array(
'start_date' => '2014-10-10',
'end_date' => '2014-10-12',
),
array(
'start_date' => '2014-10-17',
'end_date' => '2014-10-19',
),
);
$all_dates = array();
array_walk_recursive($case1, function($date) use (&$all_dates){ $all_dates[] = strtotime($date); }); // put them all inside and convert them to seconds
sort($all_dates); // normal sorting
$res1 = array('start_date' => date('Y-m-d', reset($all_dates)), 'end_date' => date('Y-m-d', end($all_dates))); // then assign the first element = start, and end element = end date
echo '<pre>';
print_r($res1);
You can use either of the built-in php array functions:
array_merge_recursive
or array_replace_recursive