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
- First post title
Date: 2017-11-28
- Second post title
Date: 2017-11-28
- 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?