How to organize database records by date when displaying in HTML view using CodeIgniter

I’m working with CodeIgniter and I have a database table that contains records sorted by date. Right now when I display the data in my HTML view, the date header shows up for every single record, which looks messy. I want to group the records so that each date appears only once as a header, with all the records for that date listed underneath it.

Here’s my current setup:

Model code:

function fetchRecords(){
  $this->db->order_by('created_date','desc');
  return $this->db->get('posts')->result();
}

Controller code:

function display(){
  $this->load->model('post_model');
  $this->data['records'] = $this->post_model->fetchRecords();

  $this->load->view('post_view', $this->data);
}

View code:

<div>
<?php
if($records){
  $current_date = '';
  foreach($records as $item){

     if(!$current_date){
       $current_date = $item->created_date; 
     }else{
       if($current_date != $item->created_date){
         $current_date = $item->created_date;
       }
     }

     echo 'Date: ' . $current_date;
     echo '<li>'.$item->post_title.'</li>';

  }
}
?>
</div>

The problem is that this shows:

Date: 2017-11-28

  1. First post title

Date: 2017-11-28

  1. Second post title

Date: 2017-11-28

  1. Third post title

I need help to properly group these records so each date header only appears once. Any suggestions on how to modify my view logic or use array functions to achieve this grouping?

Interesting approach! But what if your database returns mixed date formats - like timestamps sometimes and date format other times? And how do you handle null or empty created_date values? Just wondering how well this works in real scenarios.

just use array_column and array_unique to clean up your data in the controller first, then group by date keys before passing it to the view. way cleaner than handling all that logic on the frontend.

You’re showing the date header inside the loop every time, even when the date hasn’t changed. You need to track when the date actually changes and only show the header then.

Here’s the fix:

<div>
<?php
if($records){
  $previous_date = '';
  foreach($records as $item){
    if($previous_date != $item->created_date){
      echo '<h3>Date: ' . $item->created_date . '</h3>';
      $previous_date = $item->created_date;
    }
    echo '<li>' . $item->post_title . '</li>';
  }
}
?>
</div>

The key is comparing $previous_date with the current record’s date - only show the header when they don’t match. This works perfectly since your records are already sorted by date in descending order.