对象数组,提取最大值


Array of objects, extract highest values

给定一个存储在$my_array中的对象数组,我想提取具有最高count值的 2 个对象并将它们放在单独的对象数组中。数组的结构如下。

我该怎么做呢?

array(1) { 
     [0]=> object(stdClass)#268 (3) { 
             ["term_id"]=> string(3) "486" 
             ["name"]=> string(4) "2012" 
             ["count"]=> string(2) "40"
     } 
     [1]=> object(stdClass)#271 (3) { 
             ["term_id"]=> string(3) "488" 
             ["name"]=> string(8) "One more"
             ["count"]=> string(2) "20"  
     } 
     [2]=> object(stdClass)#275 (3) { 
             ["term_id"]=> string(3) "512" 
             ["name"]=> string(8) "Two more"
             ["count"]=> string(2) "50"  
     } 

您可以通过多种方式执行此操作。 一种相当幼稚的方法是使用 usort() 对数组进行排序,然后弹出最后两个元素:

usort($arr, function($a, $b) {
    if ($a->count == $b->count) {
        return 0;
    }
    return $a->count < $b->count ? -1 : 1
});
$highest = array_slice($arr, -2, 2);

编辑:

请注意,前面的代码使用匿名函数,该函数仅在 PHP 5.3+ 中可用。 如果您使用的是 <5.3,则可以只使用普通函数:

function myObjSort($a, $b) {
    if ($a->count == $b->count) {
        return 0;
    }
    return $a->count < $b->count ? -1 : 1
}
usort($arr, 'myObjSort');
$highest = array_slice($arr, -2, 2);

您可以使用 array_walk() 然后编写一个检查 count 值的函数。