This should work for you:
So basically you just loop through your entire array and check if the next element is still set AND the current array is the same as the next one (Which means they have the same hours). If yes you do this until the while loop returns false. Which is this code:
$DayAmountOfConsecutiveSameHours = 1;
while(isset($arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours)]) &&
($opening_hours[$arrayKeys[$dayCount]] === $opening_hours[$arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours)]]))
$DayAmountOfConsecutiveSameHours++;
Then if you have more than 1 entry you create a range from one to the other day. Which is this code:
if($DayAmountOfConsecutiveSameHours > 1)
$result[$arrayKeys[$dayCount] . " - " . $arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours-1)]] = $opening_hours[$arrayKeys[$dayCount]];
If you only have 1 day with the same hours you just add it to the results array. Which is this code:
else
$result[$arrayKeys[$dayCount]] = $opening_hours[$arrayKeys[$dayCount]];
And according to how many days the same hours have you skip the next array elements. Which is this code:
$dayCount += ($DayAmountOfConsecutiveSameHours - 1);
Full code:
<?php
$opening_hours = [
"Monday" => ["09:00", "17:00"],
"Tuesday" => ["09:00", "17:00"],
"Wednesday" => ["08:00", "13:00"],
"Thursday" => ["09:00", "17:00"],
"Friday" => ["09:00", "17:00"],
"Saturday" => ["10:00", "16:00"],
"Sunday" => ["Closed"],
];
$amountOfDays = count($opening_hours);
$arrayKeys = array_keys($opening_hours);
for($dayCount = 0; $dayCount < $amountOfDays; $dayCount++) {
$DayAmountOfConsecutiveSameHours = 1;
while(isset($arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours)]) && ($opening_hours[$arrayKeys[$dayCount]] === $opening_hours[$arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours)]]))
$DayAmountOfConsecutiveSameHours++;
if($DayAmountOfConsecutiveSameHours > 1)
$result[$arrayKeys[$dayCount] . " - " . $arrayKeys[($dayCount+$DayAmountOfConsecutiveSameHours-1)]] = $opening_hours[$arrayKeys[$dayCount]];
else
$result[$arrayKeys[$dayCount]] = $opening_hours[$arrayKeys[$dayCount]];
$dayCount += ($DayAmountOfConsecutiveSameHours - 1);
}
print_r($result);
?>
output:
Array
(
[Monday - Tuesday] => Array
(
[0] => 09:00
[1] => 17:00
)
[Wednesday] => Array
(
[0] => 08:00
[1] => 13:00
)
[Thursday - Friday] => Array
(
[0] => 09:00
[1] => 17:00
)
[Saturday] => Array
(
[0] => 10:00
[1] => 16:00
)
[Sunday] => Array
(
[0] => Closed
)
)
Demo
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…