dpw30157 2018-09-03 12:03
浏览 106
已采纳

usort不适用于laravel多维数组

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条回答 默认 最新

  • douyiken0968 2018-09-03 12:10
    关注

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

    $sorted = $collection->sortByDesc('status');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 win11安卓子系统打开谷歌登录不了切使用浏览器显示处于离线状态
    • ¥15 三维直角坐标系下,给定一个平面内四个点坐标,如何将四个点逆时针排序
    • ¥15 UnityWebRequest访问内网地址502
    • ¥20 Python语言来实现牛顿法(Newton's Method)解决非线性(系统)方程的问题。
    • ¥15 matlab控制工业相机采集图像
    • ¥25 R里做折线图和柱状图
    • ¥20 使用kokkos移植项目,遇到问题
    • ¥15 求该问题的Matlab代码
    • ¥15 python下使用pdpbox为何提示has no attribute 'pdp_isolate'?
    • ¥15 求java web病房管理系统项目,用netbeans做的