php mysql按日期输出,MYSQL PHP按日期排序并将每个日期的结果分成组

I have tried to search for a solution to my problem, but I'm not really sure what I am searching for, so I haven't had much luck.

I have a simple MySQL database with one table called "activities". In that table I have fields for "start_date", "activity_description", and "activity_location".

I am trying to do an MySQL query using PHP and display the results in ascending date order, but have all the activities that fall on the same date separated by a heading.

For example I am trying to achieve the following.

2012-05-03

Take dog for walk

Park

Go out for dinner

Little Italian Restaurant

2012-05-04

Get Car Serviced

Johns Auto and Mechanical

2012-05-05

Do Grocery Shopping

Fresh Supermarket

Go See Movie

MegaPlex Cinemas

Meet Up With Sam

Hole In The Wall Bar

So far I have worked out that the MQSQL query needs to be something like this:

$result = mysql_query("SELECT * FROM activities ORDER BY start_date ASC")

And then to display the results I need to do this:

while($row = mysql_fetch_array($result))

{

echo

'' .

$row['start_date'] .

'' .

'

  • ' .

    $row['activity_description'] .

    '

  • ' .

    $row['activity_location'] .

    '

';

}

Which gives the results like so, repeating the date for each result:

2012-05-03

Take dog for walk

Park

2012-05-03

Go out for dinner

Little Italian Restaurant

2012-05-04

Get Car Serviced

Johns Auto and Mechanical

2012-05-05

Do Grocery Shopping

Fresh Supermarket

2012-05-05

Go See Movie

MegaPlex Cinemas

2012-05-05

Meet Up With Sam

Hole In The Wall Bar

Could anyone give me some tips on how to only echo the 'start_date' once for a particular date, and then echo it again when the date is different from the previous date?

Any tips, no matter how cryptic would be greatly appreciated. Thanks.

解决方案

Just track the date.

You define a date with something that would not appear like a date in the past or just false.

Running through the lis you only print your heading when the date has changed and save the new date. Just like this:

$currentDate = false;

while($row = mysql_fetch_array($result))

{

if ($row['start_date'] != $currentDate){

echo

'' .

$row['start_date'] .

'' ;

$currentDate = $row['start_date'];

}

echo

'

  • ' .

    $row['activity_description'] .

    '

  • ' .

    $row['activity_location'] .

    '

';

}

Regards,

STEFAN

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值