[英]PHP usort() or Carbon returns incorrectly sorted array
我有一個項目正在使用Google Charts Line Graph API生成日期與數字的圖表。
我正在通過Ajax從PHP腳本向Google Chart提供數組。
一切正常,但是在數據中偶爾會出現...奇怪的地方,因為Google圖表似乎在自身上產生了環回。
我認為這是因為Google圖表依賴於其接收的JSON數組的順序(無論日期如何)。 因此,在將其發送到PHP中之前,我試圖按日期對該數組進行排序。 我在usort()內部使用一個函數來實現此目的,並使用Carbon擴展名比較日期。
// 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
,並返回到正常的排序。
這是返回給Google圖表的數組:
有誰知道為什么會這樣?
而不是對數組數據進行排序,可能更容易在繪制之前對google數據表進行排序...
data.sort([{column: 0}]);
chart.draw(data);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.