2012-02-03 4 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

이미 시간 순서대로 정렬되었으므로 루프의 순회를 통해 날짜의 1 월 부분이 바뀔 때마다 제목을 인쇄 할 수 있습니다.

예 :

// 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를 2 월 12 일로 변환하려면 어떻게해야합니까? – Prefontaine

+0

그에 따라 답변을 편집했습니다. (작동하는지 테스트하십시오.) –

+2

아주 가깝습니다. 나는 한 줄을 약간 꼬아 야했다. 에코 "

". date ("F", mktime (0, 0, 0, intval (substr ($ year_month, 5, 2)) - 1, 1, 1970)). "". " ''. substr ($ year_month, 2, 2). "

"; 도움을 주셔서 대단히 감사드립니다. 너는 신의 선물이다! – Prefontaine