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?

Community
  • 1
  • 1

2 Answers2

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;
});
Michal Brašna
  • 2,293
  • 13
  • 17
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.

Gabriel Roth
  • 1,030
  • 1
  • 12
  • 31