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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料