I have a project that is using Google Charts Line Graph API to generate a graph of Date vs Number.
I am delivering an array from a PHP script via Ajax to the Google Chart.
That all works, however there are occasionally ... oddities... in the data, in that Google Charts appears to loop-back over itself.
I think this is because Google Charts relies on the order of the JSON array it receives (regardless of Dates). So I am trying to sort this array by Date before I send it in PHP. I am using a function inside usort() to achieve this, and using the Carbon extension to compare dates.
// 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;
However, this is returning an Array where otherwise 99% correct, includes cases like: 2017-03-28
, 2017-03-29
, 2017-04-01
, 2017-03-30
, 2017-04-02
, 2017-03-31
, 2017-04-03
and returns to normal sort.
This is the returned Array to Google Charts:
Does anyone know why this would be happening?
instead of sorting the array data, probably easier to sort the google data table before drawing...
data.sort([{column: 0}]);
chart.draw(data);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.