我想以下列格式组织一系列日期。作为一个上下文,日期是我的用户可以添加的即将发生的事件的日期。格式:
2011年1月
日期 - 事件
日期 - 事件
日期 - 事件
2011年2月
日期 - 事件
日期 - 事件
日期 - 事件
包含给定月份内的所有事件,按其发生日期排列。我的所有事件日期都作为unix时间戳存储在我的数据库中。问题是,我知道id开始在哪里开发一个以这种方式排序我所有事件的函数。任何人都可以帮助我吗?
干杯
答案 0 :(得分:4)
我喜欢先使用数组索引对项目进行分组。
$months = array();
foreach ($rows as $row) {
$month = date('F Y', strtotime($row['date']);
if (!isset($months[$month]) {
$months[$month] = array();
}
$months[$month][] = $row;
}
foreach ($months as $month => $events) {
echo '<h2>' . $month . '</h2>';
foreach ($events as $event) {
// ...
}
}
答案 1 :(得分:2)
迭代事件;跟踪上次看到的MONTH。如果当前月份!=上个月,则显示月份分隔符。
$lastDate = '';
foreach ($events as $e)
{
$currDate = date('F Y', $e->date);
if ($currDate != $lastDate )
{
echo "<h1>$currDate</h1>";
}
// might want to format the date to be human readable here...
echo "<li>$e->date, $e->event";
$lastDate = $currDate;
}