我有一个数据库查询,按时间顺序显示历史事件列表,如下所示:
(URL = MySite/Calendar/January_1)<br>
On this day in history...<br>
1968 - A volcano erupted.<br>
1968 - A country was invaded.<br>
1968 - Someone had a hit song.<br>
1970 - A famous person was born.
我想知道是否有一种方法只显示一年,所以显示如下:
1968 - A volcano erupted.<br>
• A country was invaded.<br>
• Someone had a hit song.<br>
1970 - A famous person was born.
让我们从数据库表(calendar_px)开始,列出各种历史性政治事件的日期。该表有五个字段 -
1)N(简单数字键)
2)URL(值 - 例如May_1 - 匹配页面URL)
3)年份(例如1970年,但字段类型是INT,而不是年份,只能回溯到1901年)
4)简要(一些简要内容)
5)日期(字段类型将是日期或日期时间;我此刻并未实际使用此字段)
以下是我的代码的样子(其中$ MyURL等于页面网址;例如January_1):
$stm = $pdo->prepare("SELECT Cal2.N, Cal2.URL, Cal2.Date, Cal2.Year, Cal2.Brief
FROM calendar_px Cal2
WHERE Cal2.URL = :MyURL
ORDER BY Cal2.Year");
$stm->execute(array(
'MyURL'=>$MyURL
));
while ($row = $stm->fetch())
{
$Year = $row['Year'];
$Brief[] = ''.$Year.' – '.$row['Brief'].'';
}
然后,我会显示一个像这样的历史事件列表...
echo join( $Brief, '<br>' );
我认为这不会改变任何东西,但我应该提到我在几个网站上有类似的设置;除了表名之外,一切都是一样的: calendar_gw,calendar_gz,calendar_gs,calendar_px,calendar_sl
因此,我使用UNION命令加入了所有五个表。以下是查询的一部分:
$stm = $pdo->prepare("SELECT CGW.N, CGW.URL, CGW.Date, CGW.Year, CGW.Brief
FROM calendar_gw CGW
WHERE CGW.URL = :MyURL
UNION ALL
SELECT CGZ.N, CGZ.URL, CGZ.Date, CGZ.Year, CGZ.Brief
FROM calendar_gz CGZ
WHERE CGZ.URL = :MyURL
UNION ALL
SELECT CSL.N, CSL.URL, CSL.Date, CSL.Year, CSL.Brief
FROM calendar_sl CSL
WHERE CSL.URL = :MyURL
ORDER BY Year");
$stm->execute(array(
'MyURL'=>$MyURL
));
无论如何,我的目标是一样的;用某种“dingbat”或符号代替冗余日期(年)。
答案 0 :(得分:2)
$prevYear = null;
while ($row = $stm->fetch())
{
$Year = $row['Year'];
if ($Year == $prevYear) {
$YearStr = '• ';
} else {
$YearStr = $Year . ' $#8211; ';
$prevYear = $Year;
}
$Brief[] = $YearStr.$row['Brief'];
}
P.S。您不需要在字符串的每一端连接''
。
答案 1 :(得分:1)
看起来你需要在输出之前对结果集进行分组:
$events = array();
while($row = $stm->fetch()){
$year = $row['Year']; // current year
if(!isset($events[$year]){ // if no such group
$events[$year] = array(); // create group
}
$events[$year][] = $row['Brief']; // add data to year group
}
// Output:
foreach($events as $year => $event){
echo $year, ':<br>'; // show year;
foreach($event as $data){
echo $data, '<br>'; // show row;
}
}
此外,您可以轻松地将输出更改为您的模型:
foreach($events as $year => $event){
echo $year, ' • ', implode('<br>• ', $event);
}