1

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"  
     } 
0

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Worth a comment that the anonymous function will only work in PHP 5.3+
@sberry: Thanks, I'll make note of it.
0

You can use array_walk() then write a function that checks the value of count.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.