I have a date range 2023-11-01 to 2024-01-04 and some date have different MinStay value.
This is my array of date range
$input = [
[ 'date' => '2023-11-01', 'MinStay' => 1 ],
[ 'date' => '2023-11-02', 'MinStay' => 1 ],
[ 'date' => '2023-11-03', 'MinStay' => 1 ],
[ 'date' => '2023-11-04', 'MinStay' => 2 ],
[ 'date' => '2023-11-05', 'MinStay' => 2 ],
[ 'date' => '2023-11-06', 'MinStay' => 2 ],
[ 'date' => '2023-12-10', 'MinStay' => 1 ],
[ 'date' => '2023-12-11', 'MinStay' => 1 ],
[ 'date' => '2023-12-12', 'MinStay' => 3 ],
[ 'date' => '2023-12-13', 'MinStay' => 2 ],
[ 'date' => '2023-12-14', 'MinStay' => 2 ],
[ 'date' => '2024-01-01', 'MinStay' => 4 ],
[ 'date' => '2024-01-02', 'MinStay' => 4 ],
[ 'date' => '2024-01-03', 'MinStay' => 4 ],
[ 'date' => '2024-01-04', 'MinStay' => 4 ],
];
And I want to
$output = [
[ 'dateForm' => '2023-11-01', 'dateTo' => '2023-11-03', 'MinStay' => 1 ],
[ 'dateForm' => '2023-11-04', 'dateTo' => '2023-11-06', 'MinStay' => 2 ],
[ 'dateForm' => '2023-12-10', 'dateTo' => '2023-12-11', 'MinStay' => 1 ],
[ 'dateForm' => '2023-12-12', 'dateTo' => '2023-12-12', 'MinStay' => 3 ],
[ 'dateForm' => '2023-12-13', 'dateTo' => '2023-12-14', 'MinStay' => 2 ],
[ 'dateForm' => '2024-01-01', 'dateTo' => '2024-01-04', 'MinStay' => 4 ],
];
How can I solve this issue.
Thank you.
I’m try using this array but it’s not happening.
$arr = [];
foreach($input as $date) {
if($date['MinStay'] == 1) {
$arr[] = [
'dateForm' => $date['date'],
'dateTo' => $date['date'],
'MinStay' => $date['MinStay'],
];
}
}
2
Answers
A neat way to do it is to perform two loops:
First, we create a temporary array where we store elements with the key being the value of MinStay. Whenever we process a record, we check whether its MinStay was processed in an earlier record. If not, then we create such a record, with dateFrom and dateTo being the date. Otherwise, we check whether date is lesser than dateFrom, in which case we update dateFrom to it, or, if it is greater than dateTo, then we set dateTo to it.
Now we have all the groups we want, we just need to convert the format to the output you desired, so we do another loop and convert each element to the format you wanted and insert it into the output array.
Firstly, loop through the array, keep track of the current date range, and compare the
MinStay
value with the previous oneIf they are the same, extend the range, otherwise, push the current range to the output and start a new one.