2016-09-06 33 views
0

我創建了一個每月使用時間戳的計圈自動填充陣列,如2016年6月11日00:00:00 - 環路從獲取數據庫佈局是:數組循環假設無數據?

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

現在,上面的例子跳過07月(7月),本月沒有數據,所以當循環經過本月時,它應該返回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個月的數據。 99也是重複的,因爲沒有6-12個月的值,所以它使用第6個月的值而不是返回0.

如果當循環經過時沒有TimeRecord,那麼我想要它返回0,而不是假定視圖號與前一個月相同。

+0

今後沒有圖片。 Text or sqlfiddle – Drew

回答

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); 
+0

這個答案適合您的需求嗎?你能接受它還是留下評論? – trincot