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" => []
]
];
2
Answers
You can do it like this. Please read the comments within the code, and the notes below the output.
The code above outputs (verbatim, empty lines and all):
Test it here.
Notes
I’ve repacked the initial array, to make it easier to loop through it and generate an HTML string to be rendered later on. The repacking could be avoided if you control the way how the initial table (the one I dubbed
$times
in the provided code) is formed.The rendered HTML table is a barebones table – you could provide CSS classes as you loop through it, or in the opening part of the
$html
variable which contains thethead
andtbody
.Also, if you need to style the non-empty (or empty) table cells, you could do that with CSS classes as well.
The code has been adjusted to reflect on your comment – you can now provide N workslots during the day.
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. I’ll use a somewhat fancy technique to implode the time range strings using the spread operator and null coalescing so that an empty string is returned when there is no time data.
Code: (Demo)