Reverse order of archive posts

Hi folks! A while back, Bastian was kind enough to help me set up my archive page: Archive - Hicks.design.

I want to change the order of posts within each year, so that they’re in descending order. I’ve tried a few methods such as adding ->flip() but I don’t know what I’m doing.

Here’s the template code, edited for brevity :

<?php foreach ($years as $year): ?>
<div class="year">
		…
		<div class="archives">
				<?php foreach ($year['posts'] as $post): ?>
					<div>
							<p class="posted"><time><?= $post->date()->toDate('d M') ?></time></p>
							<a href="<?= $post->url() ?>" rel="bookmark">
									<?= $post->title() ?>
							</a>
					</div>
				<?php endforeach ?>
		</div>
</div>
<?php endforeach ?>

Strange, no reason why flip shouldnt work on the foreach loops

<?php foreach ($years->flip() as $year): ?>
<div class="year">
		…
		<div class="archives">
				<?php foreach ($year['posts']->flip() as $post): ?>
					<div>
							<p class="posted"><time><?= $post->date()->toDate('d M') ?></time></p>
							<a href="<?= $post->url() ?>" rel="bookmark">
									<?= $post->title() ?>
							</a>
					</div>
				<?php endforeach ?>
		</div>
</div>
<?php endforeach ?>

Although im not sure where $year['posts'] came from. Is there a controller or something matching the template? It might be best to do the flip in the controller rather than in the template.

Thanks James - putting flip after the <?php foreach ($year['posts'] results in the error:

Call to a member function flip() on array

The controller looks like this:

<?php

return function ($page) {

    $articles = pages(['journal', 'troika'])->children()->listed();
    $years = [];

    foreach ($page->children()->flip() as $year) {
        $years[$year->slug()] = [
            'summary' => $year,
            'posts'   => []
        ];
    }

    foreach ($articles as $article) {
        $year = $article->date()->toDate('Y');

        if (isset($years[$year])) {
            $years[$year]['posts'][] = $article;
        }
    }

    return [
        'articles' => $articles,
        'years'    => $years
    ];

};

This + the above template takes all my posts from the Journal and Troika sections and presents them in a list, broken up by year (with other bits of information). The Year order is flipped, but not the posts.

Ah yes thats because its not a collection.

I think you probably need to take the flip out of the template and in the controller add another flip() the to the middle for each loop

    foreach ($articles->flip() as $article) {
        $year = $article->date()->toDate('Y');

        if (isset($years[$year])) {
            $years[$year]['posts'][] = $article;
        }
    }

Spot on, thanks so much for your help James! :pray:

No problem at all :slight_smile: