给定存储的对象数组$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"
}
Run Code Online (Sandbox Code Playgroud)
你可以做很多事.一种相当天真的方式是使用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);
Run Code Online (Sandbox Code Playgroud)
编辑:
请注意,前面的代码使用匿名函数,该函数仅在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);
Run Code Online (Sandbox Code Playgroud)