简体   繁体   English

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

[英]MySQL PHP group results by date and echo them

My MySQL Table 我的MySQL表

id, message, date

date is a timestamp 日期是一个时间戳

I would like it to be echoed in PHP like this: 我希望这样在PHP中回显它:

Tuesday 20th August 2013 
- message 3
- message 2

Monday 19th August 2013 
- message 1

I have no idea how I would group the results and echo them for each day 我不知道如何将结果分组并每天回显它们

SQL Query SQL查询

SELECT id,message FROM messages ORDER BY date DESC 选择ID,来自消息的消息ORDER BY日期DESC

PHP side PHP方面

You have write a loop to print messages and write condition to "date" should not repeat again. 您已经编写了一个循环来打印消息,并且对“日期”的写条件不应再次重复。

SQL Query SQL查询

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

Now in code you get equal number of rows as dates and for each date messages as comma separate strings for example (date will be in timestamp - you can format that in code or mysql query) 现在,在代码中,您将获得与日期相等的行数,并且对于每个日期消息,将其作为逗号分隔的字符串(例如,日期以时间戳记-您可以在代码或mysql查询中设置其格式)

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

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

Loop through each record and print date and then split the messages with , (comma) and print 循环浏览每个记录和打印日期,然后用,(逗号)分隔消息并打印

<?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);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM