PHP 循环 - 调整时间轴存档页面



astheria.com 的存档页面非常好,但是对用于创建它的PHP循环有疑问。

该网站的作者发布了代码:创建时间轴样式存档页面

有一部分我不清楚。如果时间线中存在超过一年的差距(例如 2007 年的过账,然后 2008 年和 2009 年没有,然后在 2010 年再次出现),看起来此代码将打印年度标题(带有空<ol>)。

我该如何调整它以跳过这些空白的岁月?

一般逻辑可以像(半伪代码)一样简单:

$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'];
}

用词来说:

  • 从按日期排序的数据库中获取要显示的所有帖子。
  • 跟踪您输出的"当前年份"。
  • 进入新的一年后,输出它,更新当前年份。

这样,只能产出现有职位的年数。

替换了此代码块:

  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
  }

最新更新