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

4

1 回答 1

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 functionmonthly_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;

}

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

于 2013-03-01T18:18:07.370 回答