astheria.com的归档页面非常好,但对用于创建它的PHP循环有疑问。
该网站的作者发布了代码:Creating a Timeline Style Archive Page
有一部分我不清楚。如果在一年多的时间表中存在差距(例如2007年的帖子,那么2008年和2009年没有任何内容,然后在2010年再次上升),看起来此代码将打印年度标题(空{{ 1}})。
我如何调整这个以跳过这些空虚的岁月?
答案 0 :(得分:0)
一般逻辑可以像(半伪代码)一样简单:
$posts = fetchFromDatabase('SELECT * FROM `posts` ORDER BY `posted` DESC');
// $posts = array(
// array('posted' => '2010-09-13 12:42:31', 'title' => ...)
// array(...)
// )
$currentYear = null;
foreach ($posts as $post) {
$year = date('Y', strtotime($post['posted']));
if ($year != $currentYear) {
printf('<h2>%s</h2>', $year);
$currentYear = $year;
}
echo $post['title'];
}
用语言说:
这样只输出现有职位数年。
答案 1 :(得分:0)
替换了此代码块:
else if ( $prev_post_year != $post_year ) {
/* Close off the OL */
?>
</ol>
<?php
$working_year = $prev_post_year;
/* Print year headings until we reach the post year */
while ( $working_year > $post_year ) {
$working_year--;
?>
<h3 class="archive_year"><?php echo $working_year?></h3>
<?php
}
/* Open a new ordered list */
?>
<ol class="archives_list">
<?php
}
用这个来达到预期的效果:
else if ( $prev_post_year != $post_year ) {
/* Close off the OL */
?>
</ol>
<h3 class="archive_year"><?php echo $post_year?></h3>
<ol class="archives_list">
<?php
}