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: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: