簡體   English   中英

PHP usort()或Carbon返回錯誤排序的數組

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

我有一個項目正在使用Google Charts Line Graph API生成日期與數字的圖表。

我正在通過Ajax從PHP腳本向Google Chart提供數組。

一切正常,但是在數據中偶爾會出現...奇怪的地方,因為Google圖表似乎在自身上產生了環回。

日期回溯3月30日

我認為這是因為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-282017-03-292017-04-012017-03-302017-04-022017-03-312017-04-03 ,並返回到正常的排序。

這是返回給Google圖表的數組:

通過ajax返回的數組

有誰知道為什么會這樣?

而不是對數組數據進行排序,可能更容易在繪制之前對google數據表進行排序...

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

chart.draw(data);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM