Most commented topic

Hi
I would like to get the 5 most commented topics from the past month. Every comments are stored inside structures fields of pages.
So basically, I have to :

  • filter pages by date (this is ok)
  • count the comments from the structure field and sort them from the higher to lower value and limit them to 5. (this is more difficult for me)

This is actually what I have, but the pages are not sorted…

        <?php $articles = $pages->children()->visible()->filterBy('date', '<', strtotime('-1 month'));?>
        <?php foreach($articles as $article): ?>
        <?php $articlesnum = $article->comments()->toStructure()->count(); 
        if($articlesnum >= 1):
        ?>      
        <tr>
            <th>
                <?php echo $articlesnum; ?>
            </th>
            <th>
                <b><?php echo $article->title(); ?></b>
            </th>            
        </tr>
        <?php endif ?>
        <?php endforeach ?>

I tried multiples things like map() or asort() but I don’t really know the right method for this.
Any advices will be appreciated ! Thanks

If I haven’t included any typos, this should work:

<?php 
$articles = $pages
            ->children()
            ->visible()
            ->filterBy('date', '<', strtotime('-1 month')
            ->map(function($child) {
              $child->commentCount = $child->comments()->toStructure()->count(); 
              return $child;
              })
            ->sortBy('commentCount', 'desc')
            ->limit(5);
?>
        <?php foreach($articles as $article): ?>
        <tr>
            <th>
                <?php echo $article->commentCount(); ?>
            </th>
            <th>
                <b><?php echo $article->title(); ?></b>
            </th>            
        </tr>
<?php endforeach ?>

This is exactly what I was looking for, I’m always impressed by the simplicity of things. Thank you very much Sonja !
Best