微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

列出在PHP / MySQL中按天分组的日记事件

我正在尝试从MySQL数据库中列出PHP中的日记事件,但按天分组.我会解释一下.

这是我到目前为止的截图:

正如您所看到的,2012年10月23日有两个日记活动,并显示两个日历图标/表示/无论什么.我实际上希望它在左侧显示一个日历图标,但在右侧列出所有那些日期事件,直到第二天 – 如下面的a̶r̶t̶i̶s̶t̶s̶idiots印象中所示:

这是我刚刚写的代码,有人可以指出我正确的方向:

$sql = "SELECT entry_id, entry_title, entry_body, entry_date, entry_day, entry_month, entry_year ";
$sql .= "FROM pages_diary WHERE entry_month = :this_month AND entry_year = :this_year ";
$sql .= "ORDER BY entry_date DESC;";
// PDO stuff
if ($STH->rowCount() > 0) {
    while($row = $STH->fetch()):
        $this_db_month_word = mktime(0, 0, 0, $row['entry_month']);
        $this_db_month_word = strftime("%b", $this_db_month_word);
        echo '<div class="diary_events_item" id="diary_events_item_'.$row['entry_id'].'">';
            echo '<div class="diary_events_item_left">';
                echo '<div class="calendar_wrap">';
                    echo '<div class="calendar_wrap_top">';
                        echo $this_db_month_word;
                    echo '</div>';
                    echo '<div class="calendar_wrap_bottom">';
                        echo str_pad($row['entry_day'],2,'0',STR_PAD_LEFT);;
                    echo '</div>';
                echo '</div>';
            echo '</div>';
            echo '<div class="diary_events_item_right">';
                echo '<strong>'.htmlspecialchars($row['entry_title']).'</strong><br>';
                echo '<p>'.htmlspecialchars($row['entry_body']).'</p>';
            echo '</div>';
            echo '<div class="clear"></div>';
        echo '</div>';
    endwhile;
} else {
    echo '<p>There are no diary entries logged for <strong>'.$this_month_word.' '.$this_year.'</strong>.</p>';  
}

不是在寻找确切的代码(虽然那会很精简),只是解释会做,我相信我可以解决这个问题.

固定

在WHILE循环结束时,我添加了:

$last_db_day = $row['entry_day'];

然后将日历项包装在:

if ($last_db_day != $row['entry_day']) {
    echo '<div class="calendar_wrap_top">';
        echo $this_db_month_word;
    echo '</div>';
    echo '<div class="calendar_wrap_bottom">';
        echo str_pad($row['entry_day'],2,'0',STR_PAD_LEFT);;
    echo '</div>';
}

解决方法:

当您从数据库循环结果集时,跟踪您看到的最后一个entry_date,如果当前记录是针对不同的日期,则仅输出新的日历图标.

我通常这样做如下:

if ($STH->execute()) {

  // output headers

  $row = $STH->fetch();
  while ($row) {
    $current_date = $row['entry_date'];

    // output $current_date initialisation
    do {
      // output event $row
    } while ($row = $STH->fetch() and $row['entry_date'] == $current_date);
    // output $current_date termination
  }

  // output footers

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐