1
我有一個項目使用Google Charts Line Graph API來生成Date vs Number的圖形。PHP usort()或Carbon返回錯誤排序的數組
我正在通過Ajax將一個數組從PHP腳本傳遞到Google Chart。
這一切都有效,但偶爾有......古怪的......在數據中,谷歌圖表似乎環回自己。
我想這是因爲谷歌圖表依靠它接收(不論日期)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-28
,2017-03-29
,2017-04-01
,2017-03-30
,2017-04-02
,2017-03-31
,2017-04-03
並返回到正常的排序。
這是返回數組到谷歌圖表:
有誰知道爲什麼會發生?的
這並沒有過我的腦海所有,驚人的,現在我會嘗試 - 已所以一心想讓PHP工作--_- –
是的,解決了它 - 謝謝! –