Airikr
Airikr

Reputation: 6436

Add a new line upon new month in loop

I want to add a space when a new month is shown within a loop. $item['date_expires'] is shown as year, month, and day (YYYY-MM-DD) within the loop.

<?php
    foreach($get_items AS $item) {
        $current = date('m', strtotime($item['date_expires']));

        if($current != date('m', strtotime($item['date_expires']))) {
            $new_month = true;
            $current = date('m', strtotime($item['date_expires']));
        }

        echo $item['date_expires'];

        echo $new_month == true ? '<br><br>' : '';
    }
?>

Here's how it's been shown now:

2018-11-27
2018-10-26
2018-09-25
2018-04-27
2018-04-09
2018-04-09
2018-04-05
2018-04-03
2018-04-02
2018-04-01
2018-04-01
2018-04-01
2018-04-01
2018-04-01
2018-04-01
2018-04-01
2018-03-30
2018-03-28
2018-03-28
2018-03-26
2018-03-26
2018-03-23
2018-03-21
2018-03-19

I want it to list the dates like this:

2018-11-27

2018-10-26

2018-09-25

2018-04-27
2018-04-09
2018-04-09
2018-04-05
2018-04-03
2018-04-02
2018-04-01
2018-04-01
2018-04-01
2018-04-01
2018-04-01
2018-04-01
2018-04-01

2018-03-30
2018-03-28
2018-03-28
2018-03-26
2018-03-26
2018-03-23
2018-03-21
2018-03-19

What have I missed in my code?

Upvotes: 0

Views: 100

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94642

Basically because you were setting $current each time round the loop as the first thing you did the month was always the same.

See comments in code

<?php
    $current = null;    // init $current

    foreach($get_items AS $item) {
        // This set $current to the current rows date
        // every time round the loop so delete this line
        //$current = date('m', strtotime($item['date_expires']));

        if($current != date('m', strtotime($item['date_expires']))) {
            // output the newline here
            echo '<br>';
            // now reset $current to this rows dates month
            $current = date('m', strtotime($item['date_expires']));
        }

        echo $item['date_expires'];

        // now done in the loop so delete this line
        //echo $new_month == true ? '<br><br>' : '';
    }
?>

Upvotes: 1

Related Questions