Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group dates in a foreach loop [duplicate]

I want to add a new line in order to group dates within a foreach loop.

Example:

2015-11-05
2015-11-05

2015-11-07

2015-11-10
2015-11-10
2015-11-10

... and so on

As I don't know how to accomplish this and as I don't find nothing after few days of Googling, I have only the standard code for a foreach to loop the data from a database.

SELECT * FROM table ORDER BY datetime_published

foreach($rows AS $row) {
    echo $row['datetime_published'].'<br>';
}

The code above prints the dates like this:

2015-11-05
2015-11-05
2015-11-07
2015-11-10
2015-11-10
2015-11-10
... and so on

How can I accomplish this as the example shows?

Database structure

`id` int(11) NOT NULL AUTO_INCREMENT,
`id_visitor` int(11) NOT NULL,
`id_place` int(11) NOT NULL,
`id_post` int(11) NOT NULL,
`id_category` int(11) NOT NULL,
`data_cover` varchar(50) COLLATE utf32_swedish_ci NOT NULL,
`data_subject` varchar(45) COLLATE utf32_swedish_ci NOT NULL,
`data_content` text COLLATE utf32_swedish_ci NOT NULL,
`datetime_published` datetime NOT NULL,
`datetime_edited` datetime NOT NULL,
`datetime_saved` datetime NOT NULL
like image 206
Airikr Avatar asked Dec 19 '25 17:12

Airikr


1 Answers

One way to do this is to save the previous value and compare it to the current one:

$prev = NULL;
foreach($rows AS $row) {
    $curr = $row['datetime_published'];
    echo "$curr<br>";
    if ($curr != $prev) {
        echo '<br>';
        $prev = $curr;
    }
}
like image 180
Mureinik Avatar answered Dec 22 '25 11:12

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!