# Nested grouped collections

**URL:** <https://forum.getkirby.com/t/nested-grouped-collections/27654>\
**Category:** Questions\
**Tags:** v3\
**Created:** [January 22, 2023, 12:15am UTC](https://forum.getkirby.com/t/nested-grouped-collections/27654 "2023-01-22T00:15:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![benmessing](https://avatars.discourse-cdn.com/v4/letter/b/59ef9b/32.png) [@benmessing](https://forum.getkirby.com/u/benmessing)\
**Post date:** [January 22, 2023, 12:15am UTC](https://forum.getkirby.com/t/nested-grouped-collections/27654/1 "2023-01-22T00:15:25Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![texnixe](https://dub1.discourse-cdn.com/flex017/user_avatar/forum.getkirby.com/texnixe/32/5754_2.png) [@texnixe](https://forum.getkirby.com/u/texnixe)\
**Post date:** [January 22, 2023, 12:23am UTC](https://forum.getkirby.com/t/nested-grouped-collections/27654/2 "2023-01-22T00:23:18Z")

</div>

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

So like this

```auto
<?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 ?>

```

---

<div class="post-metadata">

**Author:** ![benmessing](https://avatars.discourse-cdn.com/v4/letter/b/59ef9b/32.png) [@benmessing](https://forum.getkirby.com/u/benmessing)\
**Post date:** [January 22, 2023, 1:10am UTC](https://forum.getkirby.com/t/nested-grouped-collections/27654/3 "2023-01-22T01:10:17Z")

</div>

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!
