2013-03-01 29 views
0

我想做一個循環,顯示月份鏈接旁邊的條目計數,但由於計數只是跳過一行,當查詢中沒有條目時,鏈接數不起作用。我將如何解決這個問題,因爲由於缺少行而無法進行簡單的數組循環。這是我一直想:每月循環與丟失的行

查詢結果

count month 
1 1 
63 3 
21 4 
7 5 
3 6 
6 7 

PHP

// NEW MONTH COUNT 
public function new_month_count() { 

    $year = $this->chosen_year(); 
    $main_sql = $this->month_count_sql() . " AND YEAR(exp_date) = " . $year . " GROUP BY MONTH(exp_date) ORDER BY MONTH(exp_date), month"; 
    $res = $this->conn->query($main_sql); 



    $array = array(); 
    $array[0] = 0; 
    $i = 1; 
    while ($row = $res->fetch_assoc()) { 
     $array[$i] = ($row['month'] == $i ? $row['count'] : 0); 
     $i += 1; 
    } 

    return $array; 

} 


// CREATE MONTHLY LINKS 
public function monthly_links() { 

    $count = $this->new_month_count(); 

    $months = array('','January','February','March','April','May','June','July','August', 'September','October','November','December'); 
    for ($i=1 ; $i <= 12 ; $i++) { 
     $array[] = "<a href='monthly.php?month=" . $i . "&status=3'>" . $months[$i] . " " . $this->chosen_year() . "&emsp; (" . $count[$i] . ")</a>"; 
    } 
    return $array; 

} 

輸出作品如果在查詢結果沒有跳過一個月,但如果該行被跳過,只有第6個月會顯示6個數字......奇怪。

+0

哪個RDMBS您使用的? – araknoid 2013-03-01 18:03:47

回答

1

如果我是你,我會像對待一個字典數組,並檢查結果包含當月值:

// NEW MONTH COUNT 

公共職能new_month_count(){

$year = $this->chosen_year(); 
$main_sql = $this->month_count_sql() . " AND YEAR(exp_date) = " . $year . " GROUP BY MONTH(exp_date) ORDER BY MONTH(exp_date), month"; 
$res = $this->conn->query($main_sql); 

$array = array(); 

while ($row = $res->fetch_assoc()) { 
    $array[$row['month']] = $row['count']; 
} 

return $array; 

}

//創建月度鏈接 public function monthly_links(){

$count = $this->new_month_count(); 

$months = array('','January','February','March','April','May','June','July','August', 'September','October','November','December'); 
for ($i=1 ; $i <= 12 ; $i++) { 

    $tempCount = 0; 

    if(isset($count[$i])) { 
     $tempCount = $count[$i] 
    } 

    $array[] = "<a href='monthly.php?month=" . $i . "&status=3'>" . $months[$i] . " " . $this->chosen_year() . "&emsp; (" . $tempCount . ")</a>"; 
} 
return $array; 

}

注:這不是測試,而是希望這有助於

+0

太棒了。正是我需要的!有用;謝謝。 – Tomanow 2013-03-01 18:38:38