I have a multi-dimensional array as shown below. I would like to display the data in a table, with each day of the week and its opening and closing times in one row. Expected result of the table is attached below.
I'm not familiar with arrays so I have not really tried anything worth mentioning here.
$times = [
"opening_time" => [
"monday" => ["10:30 am", "6:30 pm"],
"tuesday" => ["12:30 pm"],
"wednesday" => ["4:30 pm"],
"thursday" => ["2:30 pm"],
"friday" => ["4:00 pm"],
"saturday" => ["6:00 am"],
"sunday" => []
],
"closing_time" => [
"monday" => ["6:00 pm", "10:30 pm"],
"tuesday" => ["7:00 pm"],
"wednesday" => ["10:00 pm"],
"thursday" => ["6:30 pm"],
"friday" => ["11:00 pm"],
"saturday" => ["6:00 pm"],
"sunday" => []
]
];
In my opinion, there are far too many loops in @FiddlingAway's answer. You need one preparatory loop to count the number of needed time slots for the week. Then you need a nest loop to traverse only the opening times data.
As you traverse the opening times, access the related closing times by their shared day key and index.
Code: (Demo)
$slots = max(array_map('count', $times['opening_time']));
echo '<table>';
foreach ($times['opening_time'] as $day => $opens) {
echo "<tr><td>$day</td>";
for ($i = 0; $i < $slots; ++$i) {
printf(
'<td>%s</td>',
isset($opens[$i], $times['closing_time'][$day][$i])
? "{$opens[$i]} to {$times['closing_time'][$day][$i]}"
: ''
);
}
echo '</tr>';
}
echo '</table>';