我有一个 MySQL 表,其中包含我试图像这样显示的事件列表(不精确的格式):
2011
一月
- 一月事件 1
- 一月事件 2
- 一月事件 3
2012
三月
- 三月事件 1
- 三月事件 2
我终于能够使用下面的 PHP 来完成此任务,但我知道必须有更好的方法。正如您将看到的,有两个嵌套的 foreach
语句。 dateStart
列是一个DATE
。
$fetchEvents = $contentDB->query("SELECT id, title, description, dateStart, dateEnd, timeStart, timeEnd,
YEAR(dateStart) AS year, MONTH(dateStart) AS month, MONTHNAME(dateStart) AS monthName
FROM events_general ORDER BY dateStart");
while ($event = $fetchEvents->fetch())
{
$title = $event['title'];
$description = $event['description'];
$dateStart = $event['dateStart'];
$month = $event['monthName'];
$year = $event['year'];
$events[$year][$month][] = array(
'title' => $title,
'description' => $description,
'dateStart' => $dateStart);
}
foreach ($events as $year => $month)
{
echo "<p><strong>$year</strong>\n";
foreach ($month as $monthListing => $eventListing)
{
echo "
<p>$monthListing</p>\n
<div class=\"accordion\">\n
";
foreach ($eventListing as $event)
{
$title = $event['title'];
$description = $event['description'];
$dateStart = $event['dateStart'];
echo "
<h3><a href=\"#\">$title - $dateStart</a></h3>\n
<div>\n
$description \n
</div>\n
";
}
echo "</div>\n";
}
}
最佳答案
这将在一次迭代中完成,但您需要摆弄结束语 </div>
的位置。对于 Accordion -
$fetchEvents = $contentDB->query("SELECT id, title, description, dateStart, dateEnd, timeStart, timeEnd,
YEAR(dateStart) AS year, MONTH(dateStart) AS month, MONTHNAME(dateStart) AS monthName
FROM events_general ORDER BY dateStart");
$prevYear = '';
$prevMonth = '';
while ($event = $fetchEvents->fetch())
{
$title = $event['title'];
$description = $event['description'];
$dateStart = $event['dateStart'];
$month = $event['monthName'];
$year = $event['year'];
if ($year <> $prevYear) {
// if a new year we definitely need to close the previous accordion div
// unless it's the first iteration
if ($prevMonth) {
echo '</div><!-- close accordion div -->';
}
echo "<p><strong>$year</strong>\n";
}
if ($year <> $prevYear || $month <> $prevMonth) {
// if new month but not new year close accordion
if ($year == $prevYear) {
echo '</div><!-- close accordion div -->';
}
echo "<p>$monthListing</p>\n";
echo "<div class=\"accordion\">\n";
}
echo "<h3><a href=\"#\">$title - $dateStart</a></h3>\n<div>\n$description \n</div>\n";
$prevYear = $year;
$prevMonth = $month;
}
// add final closing div here
echo '</div><!-- close accordion div -->';
关于php - 按年、月对事件进行分组,然后列出每个事件 - PHP 和 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9846878/