在foreach循环中将日期分组 [英] Group dates in a foreach loop

查看:100
本文介绍了在foreach循环中将日期分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加新行以便在foreach循环中将日期分组.

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

示例:

2015-11-05
2015-11-05

2015-11-07

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

... and so on

由于我不知道如何完成此任务,并且经过几天的谷歌搜索后仍然一无所获,所以我只有foreach的标准代码才能从数据库中循环数据.

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?

数据库结构

`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

推荐答案

一种方法是保存以前的值并将其与当前值进行比较:

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;
    }
}

这篇关于在foreach循环中将日期分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆