I want to find an optimized way to remove dates between start date and end date in php, below how i handle it but seems timeout when there is too many days :
/**
* Get list of dates from start date and end date
* @param {string} start
* @param {string} end
* @param {string} format
* @return array
*/
function _getDatesFromRange($start, $end, $format = 'd/m/Y') {
// Declare an empty array
$array = array();
// Variable that store the date interval
// of period 1 day
$interval = new DateInterval('P1D');
$realEnd = DateTime::createFromFormat('Y-m-d', $end);
$realEnd->add($interval);
$period = new DatePeriod(DateTime::createFromFormat('Y-m-d', $start), $interval, $realEnd);
// Use loop to store date into array
foreach($period as $date) {
$array[] = $date->format($format);
}
// Return the array elements
return $array;
}
/**
* Flat an array
* @param {array} array
* @return array
*/
function _flatten($array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
// List of dates
$bookings = array(
array(
'bookable' => 'no',
'from' => '2020-08-01',
'to' => '2020-08-05'
),
array(
'bookable' => 'no',
'from' => '2020-08-15',
'to' => '2020-08-18'
),
array(
'bookable' => 'yes',
'from' => '2020-08-01',
'to' => '2020-08-31'
)
);
So to list all dates and get bookable list, i do like this :
foreach($bookings as $booking){
if($booking['bookable'] === 'yes'){
// Get an array of list of dates between start and end
$bookable[] = _getDatesFromRange($booking['from'], $booking['to']);
} else {
$not_bookable[] = _getDatesFromRange($booking['from'], $booking['to']);
}
}
if(is_array($bookable) && is_array($not_bookable)) {
$output = array_diff(_flatten($bookable), _flatten($not_bookable));
print_r($output);
}
You can test all from this url bookable dates demo, i have 2000 products and some products have a large intervals between start and end date like below, and in this case i get timeout execution, so how i can optimise above code ?
$bookings = array(
array(
'bookable' => 'no',
'from' => '2020-08-01',
'to' => '2020-08-05'
),
array(
'bookable' => 'no',
'from' => '2020-08-15',
'to' => '2020-08-18'
),
array(
'bookable' => 'yes',
'from' => '2050-08-01',
'to' => '2050-08-31'
)
);
Thanks for you helps