简体   繁体   English

PHP usort()或Carbon返回错误排序的数组

[英]PHP usort() or Carbon returns incorrectly sorted array

I have a project that is using Google Charts Line Graph API to generate a graph of Date vs Number. 我有一个项目正在使用Google Charts Line Graph API生成日期与数字的图表。

I am delivering an array from a PHP script via Ajax to the Google Chart. 我正在通过Ajax从PHP脚本向Google Chart提供数组。

That all works, however there are occasionally ... oddities... in the data, in that Google Charts appears to loop-back over itself. 一切正常,但是在数据中偶尔会出现...奇怪的地方,因为Google图表似乎在自身上产生了环回。

日期回溯3月30日

I think this is because Google Charts relies on the order of the JSON array it receives (regardless of Dates). 我认为这是因为Google图表依赖于其接收的JSON数组的顺序(无论日期如何)。 So I am trying to sort this array by Date before I send it in PHP. 因此,在将其发送到PHP中之前,我试图按日期对该数组进行排序。 I am using a function inside usort() to achieve this, and using the Carbon extension to compare dates. 我在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;

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. 然而,这将返回一个Array另有99%是正确的,包括像例: 2017-03-282017-03-292017-04-012017-03-302017-04-022017-03-312017-04-03 ,并返回到正常的排序。

This is the returned Array to Google Charts: 这是返回给Google图表的数组:

通过ajax返回的数组

Does anyone know why this would be happening? 有谁知道为什么会这样?

instead of sorting the array data, probably easier to sort the google data table before drawing... 而不是对数组数据进行排序,可能更容易在绘制之前对google数据表进行排序...

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

chart.draw(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM