2012-04-27 80 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