usort not working for laravel multidimensional arrays

天大地大妈咪最大 提交于 2019-12-11 03:58:28

问题


I have an array

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 79
                    [name] => shelin
                    [status] => 0
                )

            [1] => stdClass Object
                (
                    [id] => 80
                    [name] => shanu
                    [status] => 2
                )

            [2] => stdClass Object
                (
                    [id] => 81
                    [name] => linto
                    [status] => 2
                )

            [3] => stdClass Object
                (
                    [id] => 82
                    [name] => joseph
                    [status] => 0
                )

        )

)

I want to rearrange this array by status desc order I try

usort($usersdetailsA, function($a, $b) {
    return $a->status <=> $b->status;
});

I got an error like

usort() expects parameter 1 to be array, object given

I tried $usersdetailsA = $this->$usersdetailsA->getValues(); the i got an error like

Undefined property: TCG\Voyager\Http\Controllers\Users::$[{"id":79,"name":"shelin","status":0},{"id":80,"name":"shanu","status":"2"},{"id":81,"name":"linto","status":"2"},{"id":82,"name":"joseph","status":0}]

Expected output

Illuminate\Support\Collection Object
    (
        [items:protected] => Array
            (
                [0] => stdClass Object
                    (
                        [id] => 80
                        [name] => shanu
                        [status] => 2
                    )
 [1] => stdClass Object
                    (
                        [id] => 81
                        [name] => linto
                        [status] => 2
                    )

                [2] => stdClass Object
                    (
                        [id] => 79
                        [name] => shelin
                        [status] => 0
                    )



                [3] => stdClass Object
                    (
                        [id] => 82
                        [name] => joseph
                        [status] => 0
                    )
Any help would be appreciated.Thanks in advance

回答1:


You can sort a collection with sort methods by a given key:

$sorted = $collection->sortByDesc('status');


来源:https://stackoverflow.com/questions/52149459/usort-not-working-for-laravel-multidimensional-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!