基于子对象的值对数组进行排序

时间:2013-05-01 03:23:50

标签: php

根据'offset'值对此数组进行排序的最有效方法是什么?

Array
(
    [0] => stdClass Object
        (
            [day] => 12
            [month] => 2
            [year] => 2013
            [start] => 12:30pm
            [end] => 3:00pm
            [timestamp] => 2013-02-12 15:00:00
            [id] => 2147483647
            [offset] => -6595200
        )

    [1] => stdClass Object
        (
            [day] => 4
            [month] => 5
            [year] => 2013
            [start] => 4:00pm
            [end] => 5:00pm
            [timestamp] => 2013-05-04 17:00:00
            [id] => 538154873
            [offset] => 406800
        )

    [2] => stdClass Object
        (
            [day] => 12
            [month] => 5
            [year] => 2013
            [start] => 7:00am
            [end] => 10:30am
            [timestamp] => 2013-05-12 10:30:00
            [id] => 1738975402
            [offset] => 1074600
        )

我想从数组中返回具有最小'offset'值的项目。

usort()是一个不错的选择吗?当数组和对象混合时,它是如何工作的?

谢谢!

1 个答案:

答案 0 :(得分:4)

只要你要排序的是一个数组,它就没问题了。你可以做到

usort ($array , function($a, $b) { 
   if ($a->offset == $b->offset) {
     return 0;
   }
   return ($a->offset < $b->offset) ? -1 : 1;
});