PHP Loop - tweaking an timeline archive page
The archive page of astheria.com is excellen开发者_如何学Got, but have a question regarding the PHP loop used to create it.
The site's author posted the code: Creating a Timeline Style Archive Page
There's a part that I'm unclear on. Should there be a gap in the timeline of more than a year (such as postings for 2007, then nothing for 2008 and 2009, then picking up again in 2010), it looks like this code will print yearly headers (with an empty <ol>
).
How might I tweak this to skip these empty years?
The general logic can be as simple as (half-pseudo code):
$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'];
}
In words:
- Fetch all posts to be displayed from the database sorted by date.
- Keep track of the "current year" you're outputting.
- Upon entering a new year, output it, update the current year.
That way only the years of existing posts are output.
Replaced this code block:
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
}
With this one to achieve the desired results:
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
}
精彩评论