Reputation: 155
There is an array:
$array = [
'2020-02-07' => ['09:00' => 1500, '10:30' => 1500, '11:00' => 1500],
'2020-02-08' => ['09:00' => 1500, '09:30' => 1500, '10:00' => 1500]
];
You must create a new array under the following condition:
if the difference between the time (which is in the array keys) is 30 minutes, then write the range, and if it is more than 30 minutes, then write the same value. The result should be as follows:
$out = [
'2020-02-07' => ['09:00', '10:30 - 11:00'],
'2020-02-08' => ['09:00 - 09:30', '09:30 - 10:00']
];
My code:
$array = [
'2020-02-07' => ['09:00' => 1500, '10:30' => 1500, '11:00' => 1500],
'2020-02-08' => ['09:00' => 1500, '09:30' => 1500, '10:00' => 1500]
];
foreach ($array as $k => $a)
{
$a = array_keys($a);
while ($cur = current($a)) {
$next = next($a);
$result[$k][] = $cur . ((strtotime($next) - strtotime($cur)) === 1800 ? ' - '. $next : '');
}
}
print_r($result);
The problem is that I do not know how to delete the extra (highlighted in red) values, each current value must be checked with the previous. Tell me how you can do this?
Maybe there are ways to solve the problem easier? Thanks.
Upvotes: 1
Views: 47
Reputation: 147166
This is one way of solving the problem. While iterating through the times (but only as far as the second to last entry) in each date's values, we keep a flag which says whether the next time has been included in an interval. When we find a value which has not already been included in an interval, and is not part of an interval, we output that value, otherwise we output an interval:
$array = [
'2020-02-07' => ['09:00' => 1500, '10:30' => 1500, '11:00' => 1500],
'2020-02-08' => ['09:00' => 1500, '09:30' => 1500, '10:00' => 1500],
'2020-02-09' => ['09:00' => 1500, '09:30' => 1500, '11:00' => 1500],
'2020-02-10' => ['09:00' => 1500, '10:30' => 1500, '11:30' => 1500]
];
$result = array();
foreach ($array as $date => $arr) {
$next_included = false;
$times = array_keys($arr);
$count = count($times);
for ($i = 0; $i < $count - 1; $i++) {
$current = $times[$i];
$next = $times[$i+1];
if (strtotime($next) - strtotime($current) == 1800) {
$result[$date][] = "$current - $next";
$next_included = true;
}
else {
if (!$next_included) $result[$date][] = $current;
$next_included = false;
}
}
if (!$next_included) {
$result[$date][] = $next;
}
}
print_r($result);
Output (for my expanded demo on 3v4l.org):
Array
(
[2020-02-07] => Array
(
[0] => 09:00
[1] => 10:30 - 11:00
)
[2020-02-08] => Array
(
[0] => 09:00 - 09:30
[1] => 09:30 - 10:00
)
[2020-02-09] => Array
(
[0] => 09:00 - 09:30
[1] => 11:00
)
[2020-02-10] => Array
(
[0] => 09:00
[1] => 10:30
[2] => 11:30
)
)
Upvotes: 2