Get value of structure by checking which checkbox is selected

Hi all,

I have a structure containing checkboxes (weekdays) and textfields with times:

-
days: Mo, Tue
start: "08.00" 
end: "12.30" 
-
days: Wed, Fr 
start: "09.00" 
end: "13.30" 
-

My output should look like this:

Mo: [08.00,12.30]
Tue: [08.00,12.30]
Wed: [09.00,13.30]
Fr: [09.00,13.30]

How can I accomplish that? Before using the checkboxes I listed each weekday separately and used findBy to check the values and that worked fine but it was not as easy to use. The code used:

[<?php if($site->hours()->toStructure()->findBy('Day', 'Mo') != ''): $day = $site->hours()->toStructure()->findBy('Day', 'Mo'); ?>
  [<?= $day->start(); ?>, <?= $day->end(); ?>]
<?php endif ?>]

I hope this makes sense and tells you enough to figure out what I want to do…

UPDATE: The Problem is that findBy is looking for the exact value in “days” but I need to just check if “days” contains “Mo”…

<?php
$items = $site->hours()->toStructure();
// since there are only 7 possible days in a week, I'd use a fixed array here (shorten, if weekend is not relevant)
$days = ['Mo', 'Tue', 'Wed', 'Thu', 'Fr', 'Sat', 'Sun'];
foreach ($days as $day):
  if ($item = $items->filter(function($item) use ($day) {
    return in_array($day, $item->days()->split());
  })->first()): 
?>
  <p><?= $day . ': [' . $item->start() . $item->end() . ']'; ?></p>
  <?php endif ?>
<?php endforeach ?>

You could get the relevant days from the structure first, but I wouldn’t bother.

1 Like

Somehow I didn’t think of doing it that way but that is just perfect. Thank you!