Although the code in question is PHP, I need a second look, a general algorithm, pseudocode or something similar as a solution.
I have a collection of objects ($events
) with properties:
-
event_name
date_from
date_to
I have a table with weekdays:
Mon Tue Wed Thu Fri Sat Sun
Starts * * * * * * *
Ends * * * * * * *
Same table in HTML:
<table>
<thead>
<tr>
<th></th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
<th>Sun</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Starts</strong></td>
<td>*</td>
<td>*</td>
<td>*</td>
<td>*</td>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
<tr>
<td><strong>Ends</strong></td>
<td>*</td>
<td>*</td>
<td>*</td>
<td>*</td>
<td>*</td>
<td>*</td>
<td>*</td>
</tr>
</tbody>
</table>
Asterisk is just a placeholder and it isn't relevant.
I would like to display event_name
under e.g. Wednesday if the event starts or ends on Wednesday. Of course, if it starts on Wednesday (date_from
is a Wednesday), I would like it in the Starts
row under Wed, and if it ends on Wednesday (date_to
is a Wednesday), I would like it in the Ends
row under Wed.
I have a working solution, but it's so bad that I have second thoughts of even writing it here :)
The solution was to take that HTML and put in each <td>*</td>
instead of asterisk these lines of PHP (example for Monday's <td>
):
<td>
foreach($events as $event) {
if($event->date_to == $week_start) { //Monday is start of the week
echo $event->name;
}
}
</td>
For Tuesday's <td>
, it would be something like:
<td>
foreach($events as $event) {
if($event->date_to == $week_start + 1) { //Tuesday is start of the week + 1 day
echo $event->name;
}
}
</td>
...and so on, but 14 of these foreach
's and if
's for each day times two rows is probably as stupid as it gets :). Of course, for Ends
row I compare date_to
property to the day in question.
Does anyone have a conceptual answer? How to aproach this problem in a better way?
P.S. I'm working in Laravel, PHP MVC framework, so I'm building a collection in a controller and passing it on to the view. Dates are Carbon instances, which is a PHP API extension for DateTime so various handy methods for determining days are available (addDay()
, startOfWeek()
, etc.). The HTML in question can be changed, as can be the structure of $events
collection, if necessary.
Thank you in advance for your ideas.
EDIT: Bonus points for putting comma after each event_name
except last, in a table cell (<td>
).