2012-02-03 35 views
0

我正在嘗試爲我的網站的博客開發每月檔案的簡單列表。我已經從數據庫中抽取的記錄,現在我只需要他們據此進行排序,以便他們以這種方式出現:CodeIgniter - 月度檔案

<h4>February '12</h4> 

<ul> 
    <li>Article 1</li> 
    <li>Article 1</li> 
    <li>Article 1</li> 
</ul> 

<h4>January '12</h4> 

<ul> 
    <li>Article 1</li> 
    <li>Article 1</li> 
    <li>Article 1</li> 
</ul> 

等。

這裏是我的控制器功能,拉記錄:

public function get_archives() 

{ 

    $query = $this->db->query(" 
     SELECT id, 
     title, 
     date_published 
     FROM blog_post 
     ORDER BY date_published DESC 
    "); 

    if ($query->num_rows() > 0) 

    { 

     return $query->result(); 

    } 

} 

然後,我已通過使用$存檔這些結果我的看法。 date_published值返回例如2012-01-13 18:39:53的時間戳。

什麼是最好的方法呢?

回答

3

由於您已經按照時間順序對它們進行了排序,因此您可以在循環中遍歷它們並在日期的每年的月份部分發生更改時打印標題。

例子:

// get list of blog-items 
$archives = $this->get_archives(); 

$last_year_month = ""; 

// traverse items in foreach loop 
foreach($archives as $d) { 
    // extract year and month 
    $year_month = substr($d["date_published"], 0, 7); 

    // if year and month has changed 
    if ($year_month != $last_year_month) { 
    // if not the first heading, close previous UL 
    if ($last_year_month != "") echo "</ul>\n"; 

    $last_year_month = $year_month; 

    echo "<h4>" . date("M", mktime(0, 0, 0, intval(substr($year_month, 5, 2)) - 1, 1, 1970)) . " " . substr($year_month, 2, 2) . "</h4>\n"; 

    // opening UL for next list 
    echo "<ul>\n"; 
    } 

    echo " <li>" . $d["title"] . "</li>\n"; 
} 
// only print if an UL was opened 
if ($last_year_month != "") echo "</ul>\n"; 
+0

完美!非常感謝!最後一個問題。如何將2012-02例如轉換爲2012年2月? – Prefontaine 2012-02-03 18:05:55

+0

我已經編輯了相應的答案。 (請測試它是否有效。) – 2012-02-03 18:11:14

+2

非常非常接近。我不得不稍微調整一行。回聲「

」。日期(「F」,mktime(0,0,0,intval(substr($ year_month,5,2))-1,1 1970))。 「」。 「'」。 substr($ year_month,2,2)。 「

」; 非常感謝您的幫助。你是天賜之物! – Prefontaine 2012-02-03 18:19:31