Reputation: 115
I have a an array with opening hours structured like this:
array:7 [
"mon" => array [
"open" => null
"close" => null
]
"tue" => array [
"open" => null
"close" => null
]
"wed" => array [
"open" => "09:00"
"close" => "20:00"
]
"thu" => array [
"open" => null
"close" => null
]
"fri" => array [
"open" => "14:00"
"close" => "17:00"
]
"sat" => array [
"open" => "12:00"
"close" => "15:00"
]
"sun" => array [
"open" => "12:00"
"close" => "15:00"
]
]
I would like to create a structure like this:
array [
array [
"mon" => array [
"open" => null
"close" => null
]
"tue" => array [
"open" => null
"close" => null
]
]
array [
"wed" => array [
"open" => "09:00"
"close" => "20:00"
]
]
array [
"thu" => array [
"open" => null
"close" => null
]
]
array [
"fri" => array [
"open" => "14:00"
"close" => "17:00"
]
]
array [
"sat" => array [
"open" => "12:00"
"close" => "15:00"
]
"sun" => array [
"open" => "12:00"
"close" => "15:00"
]
]
]
Where days with the same opening hours are grouped together as long as the days are in a row. Otherwise a day should end up by itself.
I've been working on achieving this in PHP and this is what I've got so far.
$hours = [];
$previousDay = null;
foreach ($days as $key => $day)
{
if ($day === $previousDay)
{
$hours[] = array($key => $day);
}
else
{
$hours[] = array($key => $day);
}
$previousDay = $day;
}
I'm stuck on how to group days with the same opening hours together in one array.
Upvotes: 2
Views: 183
Reputation: 685
How is below?
$result = array();
$previous = null;
$idx = -1;
foreach ($days as $key => $day){
if($day !== $previous){
$idx++;
}
$result[$idx][$key] = $day;
$previous = $day;
}
Upvotes: 1