I have a string with dates separated by commas and I want to calculate if any single dates are connected.
So the list might be:
2022-07-15, 2022-07-16, 2022-07-17, 2022-07-18, 2022-07-22, 2022-07-25, 2022-07-26, 2022-07-27, 2022-07-28
What I want to achieve is that I get the interval of "concatenated" dates and then "individually" get the "single" date like this:
0 => 2022-07-15 - 2022-07-18 1 => 2022-07-22 2 => 2022-07-25 - 2022-07-28
Is it possible to calculate from a string to the output with some explosions and looping through the dates somehow?
P粉0578693482024-02-05 00:58:06
Yes, you can:
strtotime($date . ' 1 day')
to calculate the next date and verify that the next date in the sorted array matches it. If it matches the expected date, make it the second entry in the current subarray. If there is no match, start a new subarray,...etcfunction groupDates($input) { $arr = explode(", ", $input); sort($arr); $expected = -1; foreach ($arr as $date) { if (strtotime($date) == $expected) { array_splice($range, 1, 1, $date); } else { unset($range); $range = [$date]; $ranges[] = &$range; } $expected = strtotime($date . ' + 1 day'); } foreach ($ranges as $entry) { $result[] = implode(" - ", $entry); } return $result; } // Demo run $str = "2022-07-15, 2022-07-16, 2022-07-17, 2022-07-18, 2022-07-22, 2022-07-25, 2022-07-26, 2022-07-27, 2022-07-28"; $result = groupDates($str); print_r($result);