Q:

Get data from table for each month

i have table like this :
ID     Date             Content      
1   2016-07-29   content for july 29th
2   2016-07-30   content for july 30th
3   2016-08-01   content for august 1st
4   2016-08-02   content for august 2nd

and i want the result like this :
July 2016
29 July 2016 - content for july 29th
30 July 2016 - content for july 30th
August 2016
01 August 2016 - content for august 1st
02 August 2016 - content for august 2nd
i've created the manual foreach loop to show data, like this one :
my models:
public function get_july16(){
$this->db->select('*');
$this->db->from('table');
$this->db->where('month(date)','07');
$july16 = $this->db->get();
return $july16->result();
}
public function get_aug16(){
$this->db->select('*');
$this->db->from('table');
$this->db->where('month(date)','08');
$aug16 = $this->db->get();
return $aug16->result();
}

my view:
<h3>July 2016</h3>
<?php foreach($july16 as $e): ?>
<h4><?php echo $e->date;?></h4>
<div><?php echo $e->content;?></div>
<?php endforeach; ?>

<h3>August 2016</h3>
<?php foreach($aug16 as $e): ?>
<h4><?php echo $e->date;?></h4>
<div><?php echo $e->content;?></div>
<?php endforeach; ?>

i wonder if there is simplest way to do foreach loop at once instead of creating one by one.

A:

Wolfgang1983 has right.
But here is a quick solution to solve your problem. (not verified)
(You can use <?= instead of <?php echo)
$this->db->select('*');
$this->db->from('table');
$datas = $this->db->get()->result();

$months = [];
foreach ($datas as $d) {
    $date = strtotime($d->date);
    $actualMonth = date("F Y", $date); // get July 2016, August 2016...
    $months[$actualMonth][$date] = $d; // Insert data into board
}

// loop into all months
foreach ($months as $month => $days) {
    echo "<h3>$month</h3>"; // Display month
    foreach ($days as $day) {
        echo "<h4>".$day->date."</h4>";
        echo "<div>".$day->content."</div>";
    }
}

