数组循环假设没有数据?

时间:2016-09-06 12:13:35

标签: php mysql arrays loops logic

我使用时间戳在每个月的计数循环中创建了一个自动填充数组,例如2016-06-11 00:00:00 - 循环从中获取的数据库布局是:

TimeRecord          | Views 
2016-06-11 00:00:00 | 22
2016-08-11 00:00:00 | 44

现在,上面的例子跳过07(七月)月,本月没有数据,所以当循环经过这个月时,它应该返回null或0,但它返回先前已知的数字(在这种情况下是22)。

对于2016-09,没有指定数据,因此数组将给出“44”。

循环和从数据库中获取以生成数组的代码如下:

$startMonth = date("y-m-d");
$endMonth = date("y-m-d");

while ($Month <= 12){

$ViewsThisMonth = mysqli_fetch_object(mysqli_query($db, "SELECT    SUM(Views) AS NumberFinalViews, EXTRACT(YEAR_MONTH FROM TimeRecord) AS YearMonth FROM BlogViews WHERE TimeRecord > '$startMonth' AND TimeRecord < '$endMonth' GROUP BY YearMonth"));

if (is_null($ViewsThisMonth->NumberFinalViews)){
$ViewsThisMonth->NumberFinalViews = 0;
}

$ArrayTimeStamp[] = $ViewsThisMonth->NumberFinalViews;
$Month = $Month + 1;
$startMonth = date("y-m-d",strtotime("-$Month month"));
}

返回JSON编码数组的示例是:

[0,"29392","333","4000","4000","99","99","99","99","99","99","99"]

可以找到导致上述数组的数据库值的屏幕截图here。正如你所看到的,4000重复了两次,因为第5个月没有记录,导致它使用第4个月的数据。因为没有第6个月到第12个月的值,所以也会重复99,因此它使用第6个月的值而不是返回0。

如果循环经过那个月没有TimeRecord,我希望它返回0,而不是假设视图号与前一个月相同。

1 个答案:

答案 0 :(得分:1)

问题是您多次执行相同的查询,尽管日期不断变化。该查询旨在提供几个月的结果,但您只使用其中一个结果行。由于没有order by子句,可能是您以意外顺序获取行。你在循环中改变开始日期的方式也很奇怪:它会及时向后移动。

最好只执行一次查询,然后将结果存储到按月份键入的预准备数组中。

请注意,您可以使用COALESCE在SQL查询本身中执行空检查。

代码变成这样:

$startYearMonth = date('Ym', strtotime("2015-01-01")); // set this date as you wish
$endYearMonth = date('Ym', strtotime("now"));

// Prepare result array: one entry per month, with all values set to 0
for ($yearMonth = $startYearMonth; $yearMonth <= $endYearMonth; 
                                   $yearMonth += ($yearMonth % 100 == 12 ? 89 : 1)) {
    $months[$yearMonth] = 0;
}

// improved query
$result = mysqli_query($db, "
    SELECT   COALESCE(SUM(Views), 0) AS NumberFinalViews, 
             EXTRACT(YEAR_MONTH FROM TimeRecord) AS YearMonth 
    FROM     BlogViews 
    WHERE    EXTRACT(YEAR_MONTH FROM TimeRecord) 
                   BETWEEN '$startYearMonth' AND '$endYearMonth'
    GROUP BY YearMonth");

// Featch and store each result in their proper year-month slot
while ($ViewsThisMonth = mysqli_fetch_object($result)) {
    $months[$ViewsThisMonth->YearMonth] = $ViewsThisMonth->NumberFinalViews;
}

// output the result
print_r($months);
相关问题