Sampath
Sampath

Reputation: 308

data result group by date in frontend view html in codeinginter

I have table like this. The table result order by date. I'm using codeigniter framework. enter image description here

I want to print it out above result like below image. enter image description here

Today, Yesterday can be display using helper function.

Model

function getData(){
  $this->db->order_by('date','desc');
  return $this->db->get('table')->result();
}

Controller

function index(){
  $this->load->model('data_model');
  $this->data['result'] = $this->data_model->getData();

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

View

<div>
<?php
if($result){
  $date ='';
  foreach($result as $row){

     if(!$date){
       $date = $row->date; 
     }else{
       if($date != $row->date){
         $date = $row->date;
       }
     }

     echo 'Date : ' . $date;
     echo '<li>'.$row->title.'</li>';

  }
}
?>
</div>

above code display like below

Date : 2017-11-28 1. Some title A

Date : 2017-11-28 1. Some title B

Date : 2017-11-28 1. Some title C

Please help me to group this by any function or array or other.

Upvotes: 1

Views: 833

Answers (2)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

Fetching data ordered by date which is fine in view you just need to add some conditional logic to show date only once for same date records

<div>
    <?php
    if ($result) {
        $date = false;
        foreach ($result as $row) {
            if ($row->date != $date) {
                echo 'Date : ' . $date;
                $date = $row->date;
            }
            echo '<li>' . $row->title . '</li>';
        }
    }
    ?>
</div>

There is no need to use GROUP_CONCAT because at some stage it might fail or you need to adjust some Mysql configuration due to character limitation.

As per docs The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet

Or prepare your data in controller like each date array has collection of its title like

$data = array();
foreach ($result as $row) {
    $data[$row->date][] = $row->title;
}

this will produce an array like

array(
'2017-11-28' => array('some title a','some title b'),
'2017-11-29' => array('some title a','some title b')
)

Pass this $data to your view and loop through your array as

<div>
    <?php
    foreach ($data as $date => $titles) {
        echo 'Date : ' . $date;
        foreach ($titles as $title) {
            echo '<li>' . $title . '</li>';
        }
    }
    ?>
</div>

Upvotes: 2

Gyandeep Sharma
Gyandeep Sharma

Reputation: 2327

I'm giving you select query... apply it in your code accordingly...

SELECT GROUP_CONCAT(title),date
FROM table_name GROUP BY date ORDER BY date

Upvotes: 0

Related Questions