Nested grouped collections

I would like to output an index of all my blog posts on one page. The posts should be grouped by year and month. The date is stored in the format YYYY-MM-DD on the posts.

The result should look like this:

2022

02

Title
Title
Title

01

Title
Title

2021

12

Title
Title
Title

11

Title
Title

10

Title
Title
Title
Title

And so on.

I already tried the cookbook recipe “Grouping collections” and only grouped by year it works without problems. Unfortunately I lack the PHP knowledge to “nest” two groupings - all my attempts failed miserably.

Would be great if you could help me with this. Many thanks in advance!

Inside the first loop, you would group the resulting collection again, this time by month.

So like this

<?php
$groupedItems = page('notes')->children()->listed()->group(fn($p) => $p->date()->toDate('Y'));

foreach($groupedItems as $year => $itemsPerYear): ?>
  <h2><?= $year ?></h2>
  <ul>
    <?php foreach($itemsPerYear->group(fn($p) => $p->date()->toDate('F')) as $month => $itemsPerMonth) : ?>
      <li><?= $month ?>
        <ul>
          <?php foreach($itemsPerMonth as $item): ?>
            <li><?= $item->title() ?></li>
          <?php endforeach; ?>

        </ul>
      </li>
    <?php endforeach; ?>
  </ul>
<?php endforeach ?>

Thank you SO much – works perfectly!

I had messed up the second loop:
instead of
foreach($itemsPerYear
I had used
foreach ($groupedItems
again. And this of course led to all posts of the entire year being displayed for every month.

Thanks again for the quick help!