Past events grouped by year and sorted –but how to sort the years?

Hi there :slight_smile:

It’s me again with my Events page. So I have that section titled “Past Events”. They’re sorted and grouped by year. My oh so little oh so annoying problem is that I can’t sort the years numerically! (They are just sorted the way they were added in the content file.)

Here’s the code of the template:

<?php
    $events = page('events')->events()->toStructure()->filter(function($child) {
    return $child->date(null, 'enddate') < time();
    });
    $years = $events->groupBy('year');

    foreach($years as $year => $eventsPerYear): ?>

        <h1><?= $year ?></h1>
                
        <?php
            $sortedEvents = $eventsPerYear->sortBy('startdate', 'desc');
            foreach($sortedEvents as $event) : ?>

            <div class="event">
            …
            </div>

            <?php endforeach; ?>
            
    <?php endforeach ?>

Thank you in advance for your help!
Cheers,
Daniel

Sort them first and then group them:

 $events = page('events')->events()->toStructure()->filter(function($child) {
    return $child->date(null, 'enddate') < time();
    })->sortBy('year'); //add sort order if required, default is 'asc'
$years = $events->groupBy('year');
1 Like

Oh well, it seems all so obvious now. I was so focused on trying to sort the $years that I didn’t realize that sorting the $events first would be the right approach. Sigh.
Thank you texnixe and have an enjoyable week!
Daniel

Cheer up, sometimes you just don’t see the forest for the trees :wink:

That’s right, in French we phrase it in the same way: “C’est l’arbre qui cache la forêt.”