0

I have an array resulted from external API. I want to sort this array using ASC format, but when test it on my function, The sorted result is same like my array data. It is not sorted. I am using Laravel 5.7 to do this.

This is my function :

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";
    }
}

This is the result :

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

Something wrong with my function? How to fix this?

3
  • 1
    Please correct your code first. Your $arrayData is not in PHP syntax. Commented Sep 6, 2019 at 8:07
  • 1
    use sortBy($value['type'], SORT_NATURAL, true) Commented Sep 6, 2019 at 8:07
  • @RahmatEffendi Show your expected result. Also, are those json strings or actual PHP arrays? Commented Sep 6, 2019 at 8:16

1 Answer 1

1

you can use sort by in laravel

$sorted = collect($arrayData)->sortBy('type');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.