2012-02-03 11 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を2010年2月に変換するにはどうすればよいですか? – Prefontaine

+0

私はそれに応じて答えを編集しました。 (動作すればテストしてください) –

+2

非常に、非常に近いです。私はわずかに一つの行を微調整しなければならなかった。エコー "

"。 date( "F"、mktime(0、0、0、intval(substr($ year_month、5、2)) - 1,1,170)。 "" "'' substr($ year_month、2、2)。 "

"; ご協力いただきありがとうございます。あなたは神様です! – Prefontaine

関連する問題