缺少行的每月循环

时间:2013-03-01 18:01:03

标签: php sql

我正在尝试执行一个循环,显示月份链接旁边的条目计数,但由于计数只是在查询中没有条目时跳过一行,因此链接的计数不起作用。我将如何解决这个问题,因为由于缺少行而无法进行简单的数组循环。这是我一直在尝试的:

查询结果

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 ...奇怪的数量。

1 个答案:

答案 0 :(得分:1)

如果我是你,我会将数组视为字典,并检查结果是否包含该月的值:

// 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();

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;

}

注意:这未经过测试,但希望这有帮助