2017-04-20 45 views
1

我有一個項目使用Google Charts Line Graph API來生成Date vs Number的圖形。PHP usort()或Carbon返回錯誤排序的數組

我正在通過Ajax將一個數組從PHP腳本傳遞到Google Chart。

這一切都有效,但偶爾有......古怪的......在數據中,谷歌圖表似乎環回自己。

Dates March 30 is looping back

我想這是因爲谷歌圖表依靠它接收(不論日期)JSON數組的順序。所以我試圖按照Date對數組進行排序,然後再用PHP發送它。我正在使用usort()中的函數來實現此目的,並使用Carbon extension來比較日期。

// Sort by Date 
usort(
    $rows, 
    function ($a, $b) { 
     // 'date' Index in $row array 
     $date = 0; 

     // Match for anything within Brackets (only match should be 'Date(xxx)' column of $row); 
     preg_match('#\((.*?)\)#', $a[$date], $a_matches); 
     preg_match('#\((.*?)\)#', $b[$date], $b_matches); 

     // If $a and $b contain Dates (as assumed by above) ie. not header/information rows 
     if (isset($a_matches[1]) && isset($b_matches[1])) { 
      // Convert the strings to Dates and increase 
      $a_date = Carbon::parse(str_replace(', ', '-', $a_matches[1]))->addMonth(); 
      $b_date = Carbon::parse(str_replace(', ', '-', $b_matches[1]))->addMonth(); 

      // If $a less than $b, return -1 (reduce $a in order) otherwise 1 (promote $a in order) 
      if ($a_date->lt($b_date)) return -1; 
      else return 1; 
     } 

     // Else return 0 (no change in order) 
     return 0; 
    } 
); 

return $rows; 

然而,這將返回一個Array另有99%是正確的,包括像例: 2017-03-282017-03-292017-04-012017-03-302017-04-022017-03-312017-04-03並返回到正常的排序。

這是返回數組到谷歌圖表:

array returned via ajax

有誰知道爲什麼會發生?的

回答

2

,而不是排數組數據,可能更容易繪製前谷歌的數據表進行排序...

data.sort([{column: 0}]); 

chart.draw(data); 
+0

這並沒有過我的腦海所有,驚人的,現在我會嘗試 - 已所以一心想讓PHP工作--_- –

+0

是的,解決了它 - 謝謝! –