Roots Discourse

Best practice to extract and isolate post data in array_map() using array_unique() within controllers

Hi all,

Thanks for all the great work y’all are doing here.

I am new so I am struggling in extracting data using controllers based on the array_map() recommendation.

Basically I am trying to build tabs to display all the posts sorted by year like this:
image

To remove ‘years’ duplicates, I tried using array_unique() to encapsulate the array_map. I have three test posts under the news category:

  • 2021 - first post
  • 2021 - second post
  • 2020 - third post

So I was expecting to see two tabs like shown in the picture above, but instead it is only showing 2021 like this:
image

My code is below. Please advise. Thanks!

Controllers/App.php

<?php
namespace App\Controllers;
use Sober\Controller\Controller;
class App extends Controller
{
public function newsArchive() {
      $news_items = get_posts([
          'post_type' => 'post',
          'category_name' => 'news',
      ]);
      return array_unique(array_map(function ($post) {
          return [
            'year' => apply_filters('the_content', date ('Y', strtotime($post->post_date))),
          ];
      }, $news_items));
  }
}

template-news.blade.php

  <ul uk-tab="animation: uk-animation-slide-bottom-medium" class="uk-flex-left uk-tab">
    @foreach($news_archive as $news_item)
      @if ( !empty( $news_item ) ) 
    <li><a href="#">{!! $news_item ['year'] !!}</a></li>
    @endif
    @endforeach
  </ul>

Actually I found a solution from Stack Overflow. Basically adding SORT_REGULAR fixes it.

So the updated version looks like this:

Controllers/App.php

public function newsArchive() {
      $news_items = get_posts([
          'post_type' => 'post',
          'category_name' => 'news',
      ]);
      return array_unique(array_map(function ($post) {
          return [
            'year' => apply_filters('the_content', date ('Y', strtotime($post->post_date))),
          ];
      }, $news_items), SORT_REGULAR);
    }