Group articles by year and by future date

Struggling a bit to figure this out. I have an events page that groups events under year headings. This works fine. What i want to do is automatically filter out events that are now in the past. Based on the forum and the documentation, im tying this but fo some reason it only works if set the less then rather then greater then. Confusing!

<?php
$callback = function($p) {
    // return $p->date('F', 'startdate'); // by month
    return $p->date('Y', 'startdate'); // by year
};

$groupedEvents = $site->find('events')->children()->sortBy('startdate', 'asc')->group($callback)->filter(function($child) {
                return $child->date(null, 'startdate') < time();
              });
 ?>

I am listing them out like this…

<div class="all-events">

  <?php foreach($groupedEvents as $month => $events): ?>
  <header class="month-header"><h2><?= $month ?></h2></header>


  <div class="events--list">

    <?php
      // loop through the events
      foreach($events as $event):

        $estartdate = $event->startdate();
        $estarttime = $event->starttime();
        $estartisoDate = date('Y-m-d\TH:i:s', strtotime("$estartdate $estarttime"));
        $englishdate = date('l, F j: g:ia', strtotime($estartisoDate));


      ?>
    <!-- LOOP -->
    <div class="event--item">
      <a href="<?= $event->url() ?>"><img class="event-thumb" src="<?= $event->poster()->toFile()->url() ?>"></a>
      <h3><?= $event->title() ?></h3>
      <h4><?= $englishdate ?></h4>
      <?= $event->summary() ?>
    </div>
    <!-- E LOOP -->
  <?php endforeach ?>

  </div>
  <?php endforeach ?>
</div>

How can i make it work?

It would make more sense to filter first, then group. That should also fix your issue. Performance-wise I’m not sure if sort-filter-group or filter-sort-group is the better alternative. I’d probably filter first.

@jimbobrjames Is this solved?

Haven’t had a chance to try it yet. Give me a few minutes…

Yup… this seems to work…

<?php
$callback = function($p) {
    // return $p->date('F', 'startdate'); // by month
    return $p->date('Y', 'startdate'); // by year
};
$collection = $site->find('events')->children();
$filteredEvents = $collection->filter(function($child) {return $child->date(null, 'startdate') > time(); });
$groupedEvents = $filteredEvents->sortBy('startdate', 'asc')->group($callback);
?>