2017-07-25 19 views
0

我目前正在爲我們的工作網站構建一個分析系統,我們有時間戳的應用程序數據庫。Laravel Report Analytics - 緩慢的foreach查詢循環

我試圖得到每天與特定月份的應用程序的數量,我使用ajax和圖表js這樣做,代碼工作,但是,PHP是非常緩慢,我只是想知道是否有反正改善這個。下面是我使用的代碼:

$days = cal_days_in_month(CAL_GREGORIAN,$qmonth,$qyear); 
    foreach (range(1, $days) as $key => $number) { 
     $count = App\report::whereYear('date_created', $qyear)->whereMonth('date_created', $qmonth)->whereDay('date_created', $number)->count(); 
     $cart[] = array('day' => $number, 'count' => $count); 
    } 
    $result = json_encode($cart); 
    print_r($count); 

我傳遞兩個網址參數的PHP代碼$ qmonth和$ qyear,我運行取決於有多少天是在本月28日和31倍之間的查詢,因爲我需要每天統計應用程序的數量。有沒有什麼我可以做到這一點,而不必在循環中查詢30次,因爲我認爲這就是爲什麼查詢如此緩慢?

最好的問候, 加雷思

+0

30個查詢單個請求的工作絕對是一個不少。你可以做的是** 1)**編寫一個複雜的SQL查詢,它返回你已經計算和分組的MySQL或**的所需結果** **從'應用程序\報告'的所有結果與一個查詢和用PHP來轉換它們以適應圖表的抽象。 – TheFallen

+0

我將如何去做第二個選擇? –

+0

爲什麼你不通過MYSQL獲得結果,然後迭代db上的結果?當你在較低層次上工作時,速度會更快。 –

回答

0

我設法得到它使用此代碼

$cart = []; 
    $days = cal_days_in_month(CAL_GREGORIAN, $qmonth, $qyear); 
    $reports = App\report::whereYear('date_created', $qyear)->whereMonth('date_created', $qmonth)->select('date_created')->get(); 
    if ($reports->count()) { 
    }else{ 
    $items = array(); 
    } 

    foreach($reports as $i){ 
     $items[] = $i['date_created']->format('j'); 
    } 


    $countarray = array_count_values($items); 

    foreach (range(1, $days) as $day) { 
     $count = isset($countarray[$day]) ? $countarray[$day] : 0; 
     $cart[] = ['day' => $day, 'count' => $count]; 
    } 

    $result = json_encode($cart); 
    print_r($result); 
0

這是你將如何去完成所有結果的PHP轉變:

$cart = []; 
$days = cal_days_in_month(CAL_GREGORIAN, $qmonth, $qyear); 
$reports = App\report::whereYear('date_created', $qyear)->whereMonth('date_created', $qmonth)->get(); 
$reports = $reports->groupBy(function ($report) { 
    return date('d', $report->date_created); 
})->toArray(); 

foreach (range(1, $days) as $day) { 
    $count = isset($reports[$day]) ? count($reports[$day]) : 0; 
    $cart[] = ['day' => $day, 'count' => $count]; 
} 

$result = json_encode($cart); 
print_r($count); 

注意,在$reports收集使用groupBy當你不得不返回報告當天。我不確定你使用的是什麼格式,但如果是時間戳,你可以使用date函數格式化它以返回一天,如示例所示。

讓我知道這運行得有多快。

編輯:

如果DATE_CREATED是碳的實例,從報道中收集groupBy方法返回$report->date_created->format('d');

+0

獲取此錯誤日期()期望參數2爲整數,對象給定 –

+0

@GarethJones在groupBy方法中用'return $ report-> date_created替換'date('d',$ report-> date_created)'調用 - >格式( 'd');'。這是因爲你的* date_created *屬性很可能是碳實例。 – TheFallen

+0

由於某種原因,計數返回零這裏是一個輸出[{「day」:1,「count」:0},{「day」:2,「count」:0},{「day」:3,「count 「:0},{」 天 「:4」,計數 「:0},{」 天 「:5」,計數 「:0},{」 天 「:6,」 計數 「:0},{」 天「:7,」 計數 「:0},{」 天 「:8中,」 計數 「:0},{」 天 「:9」,計數 「:0},{」 天 「:10,」 計數「: 0},{ 「天」:11, 「計數」:0},{ 「天」:12, 「計數」:0},{ 「天」:13, 「計數」:0},{ 「天」: 14, 「計數」:0},{ 「天」:15, 「計數」:0},{ 「天」:16, 「計數」:0},{ 「天」:17, 「計數」:0} ,{ 「天」:18, 「計數」:0},{ 「天」:19, 「計數」:0},{ 「天」:20, 「計數」:0},{ 「天」:21, 「計數」:0},{ 「天」:22, 「計數」:0},{ 「天」:23, 「計數」:0},{ 「天」:24, 「計數」:0} .. 。 –