按日期分组在php / mysql中

时间:2011-07-16 01:47:02

标签: php mysql

我有一个数组:

Array
(
    [0] => Array
        (
            [id] => 53
            [product] => something
            [price] =>  £78
            [quantity] => 23
            [time] => 2011-07-15 20:29:21
        )

    [1] => Array
        (
            [id] => 52
            [product] => product
            [price] => £89
            [quantity] => 1
            [time] => 2011-07-14 00:51:57
        )

    [2] => Array
        (
            [id] => 51
            [product] => product
            [price] => £89
            [quantity] => 1
            [time] => 2011-07-14 00:51:37
        ))

我使用以下sql语句得到了这个:

select * from some_table GROUP BY time DESC

我想显示按日期排序的结果,日期为标题:

e.g。

**2011-07-15**
all array elements for above date go here

**2011-07-15**
all array elements for above date go here

我想过为每个单独的日做一个单独的陈述,但这听起来不对。还有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

您的查询中的ORDER BY时间,如下所示:

select * from some_table ORDER BY time DESC

然后在PHP中循环:

$last_date = 0;
while($row = mysql_fetch_assoc($result)){
    $date = date('Y-m-d', strtotime($row['time']));
    if($date != $last_date)
        echo '**'.$date.'**';
    $last_date = $date;
    echo '<br />';
    echo 'Id: '.$row['Id'];
    echo 'Product: '.$row['product'];
    echo 'Price: '.$row['price'];
    echo 'Quantity: '.$row['quantity'];
    echo '<br /><br />';
}

如果您要输入控制台而不是HTML页面,请将'<br \>'替换为"\n"

答案 1 :(得分:0)

<?
$arrDate = Array
(
    [0] => Array
        (
            [id] => 53
            [product] => something
            [price] =>  £78
            [quantity] => 23
            [time] => 2011-07-15 20:29:21
        );


$currentDate = null;

foreach ($arrDate as $item) {

      if ($item["time"] == $currentDate) {
          // print details
      }
      else {
           $currentDate = $arrDate["time"];
           // print date header.
           // print details
      } 

}

?>