如何在 Laravel 5.7 中对数组进行排序

我有一个由外部 API 产生的数组。我想使用 ASC 格式对此数组进行排序,但是在我的函数上对其进行测试时,排序结果与我的数组数据相同。它没有排序。我正在使用 Laravel 5.7 来做到这一点。


这是我的功能:


public function sortData(){


    $arrayData = [

        {"id":"950328","type":"CMATYPE ","num":"10"},

        {"id":"950328","type":"CM007","num":"20"},

        {"id":"950328","type":"CM021B ","num":"30"},

        {"id":"950328","type":"CM047","num":"40"},

        {"id":"950328","type":"CM-MMFGF","num":"50"},

        {"id":"950328","type":"CM152","num":"60"},

        {"id":"950328","type":"CM179 ","num":"70"},

        {"id":"950328","type":"CM029A","num":"80"},

        {"id":"950328","type":"CM033C ","num":"90"},

        {"id":"950328","type":"CM033E","num":"100"},

        {"id":"950328","type":"CM001 ","num":"110"},

        {"id":"950328","type":"CM012","num":"120"},

        {"id":"950328","type":"CM202 ","num":"130"},

        {"id":"950328","type":"CM203","num":"140"},  

        {"id":"950328","type":"CM205 ","num":"150"},

        {"id":"950328","type":"CASE","num":"160"}

    ];


    foreach ($arrayData as $key => $value){

        $sorted = collect($value)->sortBy($value['type']);

        echo "Data From Server : ".$sorted['type']."\n";

    }

}

这是结果:


Data From Server : CM007

Data From Server : CM021B

Data From Server : CM047

Data From Server : CM-MMFGF

Data From Server : CM152

Data From Server : CM179

Data From Server : CM029A

Data From Server : CM033C

Data From Server : CM033E

Data From Server : CM001

Data From Server : CM012

Data From Server : CM202

Data From Server : CM203

Data From Server : CM205

Data From Server : CASE

我的功能有问题吗?如何解决这个问题?


慕标5832272
浏览 244回答 1
1回答

慕盖茨4494581

你可以在 Laravel 中使用sort by$sorted = collect($arrayData)->sortBy('type');
打开App,查看更多内容
随时随地看视频慕课网APP