Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I seen this post PHP, sort array of objects by object fields and it works great for me, but I need help one step further.

Here code sample

 Array
(
    [0] => stdClass Object
        (
            [ID] => 1
            [name] => Mary Jane
            [count] => 420
        )

    [1] => stdClass Object
        (
            [ID] => 2
            [name] => Johnny
            [count] => 234
        )

    [2] => stdClass Object
        (
            [ID] => 3
            [name] => Kathy
            [count] => 4354
        )

   ....

I want to be able to remove array object that has count above 450. How could I do this? So basically it removes ([2] => stdClass Object) and etc.

Function I am using is this

function cmp($a, $b)
{
    return strcmp($a->name, $b->name);
}

usort($your_data, "cmp")

So how could I go about doing this? Do I use the unset($text) command to do this?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

You can use array_filter() to remove items from array.

$arr = array( ... );
// sort array with your usort
...
// filter array to new one
$filteredArr = array_filter($arr, function($item) {
    return $item->count <= 450;
});
share|improve this answer

You can't use usort() to remove members from the array being sorted. Your best bet would be to first use array_filter() to remove the objects with counts above 450, then sort the result.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.