Given an array of objects stored in $my_array
, I'd like to extract the 2 objects with the highest count
value and place them in a separate object array. The array is structured as below.
How would I go about doing that?
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"
}
You can do this many ways. One rather naive way would be to use usort()
to sort the array, and then pop off the last two elements:
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);
Edit:
Note that the previous code uses an anonymous function, which is only available in PHP 5.3+. If you're using < 5.3, you can just use a normal function:
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);
You can use array_walk() then write a function that checks the value of count.