2012-04-27 82 views
1

给定存储在$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" 
    } 

回答

5

您可以通过多种方式做到这一点。一个比较简单的方式是使用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); 
+2

值得评论匿名函数将只在PHP工作5.3+ – sberry 2012-04-27 16:07:48

+0

@sberry:谢谢,我会予以注意。 – FtDRbwLXw6 2012-04-27 16:09:21

+0

+1 - 对我来说很不错。 – sberry 2012-04-28 01:16:40