-1

Lets say my array is this:

[
        {
            "uid": 85,
            "priority": 3,
            "events_count": 2
        },
        {
            "uid": 83,
            "priority": 1,
            "events_count": 5
        },
        {
            "uid": 50,
            "priority": 2,
            "events_count": 1
        }
    ]

What i want to do is sort by "priority" Property of objects in a descending order. This part is accomplished and works with the code below.

usort($users, function($a, $b)
        {
            return strcmp($a->priority, $b->priority)*-1;
        });

So far so good. Now i want to set an overwriting sort which puts all items with events_count > 4 at last position. This i am not sure even how to start. Preferably i would do both logic inside the usort. Is that possible and how would i do that?

Thanks

jhon dano
  • 660
  • 6
  • 23
  • 2
    You just need a bunch of `if..else`… If `$a` has > 4 and `$b` does not, `$a` is larger, or vice versa, or if both are < 4 or both are > 4, sort by priority. – deceze Dec 14 '18 at 10:53
  • please elaborate with code example since i don't fully understand what you mean? – jhon dano Dec 14 '18 at 10:55

1 Answers1

0

@deceze has this right. You just need to add the logic to your usort call.

usort($arr, function($a, $b) {

    // If a has an events count greater than 4. But b does not
    if ($a->events_count > 4 && $b->events_count <=4) {
        // Put A after B
        return 1;
    }

    // Reverse of the above logic
    if ($b->events_count > 4 && $a->events_count <=4) {
        return -1;
    }

    // At this point either both of them are greater than 4 or neither of them 
    // are. Either way sort by priority
    return strcmp($a->priority, $b->priority)*-1;
});

There are likely more succinct ways of writing this. But this way makes it very easy to interpret.

Leigh Bicknell
  • 854
  • 9
  • 19