How can PHP loops be nested to achieve a specific layout, such as displaying dates only once for multiple events on the same day?
To display dates only once for multiple events on the same day, you can achieve this by using nested PHP loops. The outer loop can iterate through all events, while the inner loop can check if the date has already been displayed. If the date has not been displayed yet, it will be displayed and a flag will be set to indicate that it has been shown. This way, each date will only be displayed once, even if there are multiple events on the same day.
$events = array(
array('date' => '2022-01-01', 'title' => 'Event 1'),
array('date' => '2022-01-01', 'title' => 'Event 2'),
array('date' => '2022-01-02', 'title' => 'Event 3')
);
$displayedDates = array();
foreach ($events as $event) {
if (!in_array($event['date'], $displayedDates)) {
echo "<h2>{$event['date']}</h2>";
$displayedDates[] = $event['date'];
}
echo "<p>{$event['title']}</p>";
}