MySQL PHP组按日期结果并回显它们

时间:2013-08-20 11:42:09

标签: php mysql timestamp

我的MySQL表

id, message, date

日期是时间戳

我希望它能像PHP一样回应:

Tuesday 20th August 2013 
- message 3
- message 2

Monday 19th August 2013 
- message 1

我不知道如何将结果分组并每天回复它们

3 个答案:

答案 0 :(得分:0)

SQL查询

SELECT id,message FROM messages ORDER BY date DESC

PHP方

您已经编写了一个循环来打印消息,并且将条件写入“日期”不应该再次重复。

答案 1 :(得分:0)

SQL查询

select group_concat(message), date from table group by date order by date

现在在代码中,您获得与日期和每个日期消息相同的行数,例如逗号分隔字符串(日期将在时间戳中 - 您可以在代码或mysql查询中格式化)

2013年8月20日|消息3,消息1

2013年8月19日|消息2,消息4

循环浏览每个记录并打印日期,然后用,(逗号)和打印

分割消息

答案 2 :(得分:0)

<?php
$query = mysql_query("SELECT id,message FROM messages ORDER BY date DESC");
$data = array();
while($row = mysql_fetch_assoc($query)){
    $date = date("F j,Y",strtotime($row['date']));
    if(array_key_exists($date,$data)){
        $data[$date][] = array(
            'id'      => $row['id'],
            'message' => $row['message'],
        );
    }else{
        array_push($data,$data[$date]);
        $data[$date][] = array(
            'id'      => $row['id'],
            'message' => $row['message'],
        );
    }
}
echo '<pre>';
print_r($data);
?>