我正在尝试从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
}