PHP-按对象属性对对象数组进行排序 [英] PHP - Sorting an array of objects by object property

查看:1225
本文介绍了PHP-按对象属性对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信你很好.

我想尝试根据对象的score属性对该数组进行排序.下面是数据(print_r)的示例.

I would like to try and sort this array by the score property of the object. Below is an example of the data (print_r).

Array
(
    [0] => stdClass Object
        (
            [device] => 352454530452548
            [reg] => MAM 432A
            [distance] => 823.36
            [ha_points] => 1
            [hb_points] => 235
            [hc_points] => 7.5
            [idling_points] => 111.5
            [speeding_points] => 168
            [total] => 523
            [score] => 68.239895064127
        )

    [1] => stdClass Object
        (
            [device] => 3518020541565265
            [reg] => SM** ***
            [distance] => 851.07
            [ha_points] => 14
            [hb_points] => 136
            [hc_points] => 6
            [idling_points] => 50
            [speeding_points] => 336
            [total] => 542
            [score] => 68.957730856451
        )

分数可以是0到100之间的任何值,我想按降序对它们进行排序(首先是最大的?).使事情变得更复杂的是,尽管机会非常渺茫,但有可能获得两个相同的分数,在这种情况下,哪个是第一并不重要.

The score can be anything from 0 to 100 and I would like to sort them into descending order (biggest first?). To make things more complicated, although the chances are very slim it is possible to have two identical scores in which case it doesn't matter which one is first.

有什么想法吗?

预先感谢

保罗

推荐答案

一个简单的 将完成这项工作.

A simple usort will do the job.

$arrData = array(/* ... */);
usort($arrData, function($a, $b) {
    return $a->score < $b->score ? 1 : -1;
});

这篇关于PHP-按对象属性对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆