0

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?

2 Answers 2

2

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

Comments

0

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.

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.