PHP博客,需要做一个漂亮的存档部分 [英] PHP Blog, need to make a good looking archives section
问题描述
所以!基本上,我有一个带有大量博客文章的数据库,所有这些文章均按UNIX时间戳进行排序,而我需要的是一种使代码在适当的时候吐出标题的方法,以便其输出类似以下内容:
So! Basically I have a database with a load of blog posts, these are all sorted by a UNIX timestamp, and what I need is a way to make this code spit out headers when appropriate, so that it will output something like this:
标题1-日期在这里
标题2-日期在这里
Title 1 - Date Goes Here
Title 2 - Date Goes Here
标题3-日期在这里
Title 3 - Date Goes Here
标题4-日期在这里
Title 4 - Date Goes Here
等
到目前为止,这是我的代码,它可以一直工作到一年中的比较,而我仍然需要想出一种明智的方式来比较月份,以便一月确实在十二月之后,并且并非可笑的第13个月.
Here's my code so far, it works until the comparison of the year, and I still need to come up with a good way of how to make it compare months in a sensible fashion, so that January indeed comes after December, and not some ludicrous 13th month.
[代码]
<?php
if ($db = new PDO('sqlite:./db/blog.sqlite3')) {
$stmt = $db->prepare("SELECT * FROM news ORDER BY date DESC");
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
$current_year = date("Y", $row[1]);
$current_month = date("m", $row[1]);
if ($current_year > $last_year) {
echo "<h1>" . $current_year . "</h1>";
$last_year = $current_year;
}
echo "<tr>";
echo "<td align='left'><a href='view_post.php?post_id=". $row[1] ."'>" . $row['0'] . " - " . date("Y-m-d, H:i:s", $row[1]) . "</a></td>";
echo "</tr>";
}
}
} else {
die($sqliteerror);
}
?>
[/code]
推荐答案
使用unix时间戳,您可以执行类似操作(显然是伪代码)
With unix timestamps you could do something like (pseudo code obviously)
prev_month = null
prev_year = null
foreach results as r
new_month = date('F', r[timestamp]);
new_year = date('Y', r[timestamp]);
if(prev_month != new_month)
//display month
/if
if(prev_year != new_year)
//display year
/if
// display other info
prev_month = new_month
prev_year = new_year
/foreach
这篇关于PHP博客,需要做一个漂亮的存档部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!