在对象数组上使用usort

时间:2015-07-27 15:23:31

标签: php arrays usort

我有以下示例数组:

  Array
(
    [0] = Array
        (
            [Campaign] = Array
                (
                    ...
                    [views] = 10
                )
        )

    [1] = Array
        (
            [Campaign] = Array
                (
                    ...
                    [views] = 0
                )
        )

    [2] = Array
        (
            [Campaign] = Array
                (
                    ...
                    [views] = 1
                )

        )

    ...

)

我希望能够通过'views'选项对数组进行排序,所以我写了以下内容:

class DashboardController {
...
    public function recruitment_index(){
        ...
        usort($mostviewed, array('DashboardController','sort_objects_by_views'));


        ...
    }

    ...
    function sort_objects_by_views($a, $b) {
        if($a->Campaign->views == $b->Campaign->views){ return 0 ; }
        return ($a->Campaign->views < $b->Campaign->views) ? -1 : 1;
    }
}

但是我收到以下错误:

Notice (8): Trying to get property of non-object [APP/Controller/DashboardController.php, line 60]

第60行是if($a->Campaign->views == $b->Campaign->views){ return 0 ; }

1 个答案:

答案 0 :(得分:0)

您已经说过,您的数据是一个数组。所以你应该以正确的方式访问它:

class DashboardController {
...
    public function recruitment_index(){
        ...
        usort($mostviewed, array('DashboardController','sort_objects_by_views'));


        ...
    }

    ...
    function sort_objects_by_views($a, $b) {
        if($a['Campaign']['views'] == $b['Campaign']['views']){ return 0 ; }
        return ($a['Campaign']['views'] < $b['Campaign']['views']) ? -1 : 1;
    }
}