如何基于2个属性值通过组合逻辑对对象数组进行排序?

时间:2018-12-14 10:49:08

标签: php

让我们说我的数组是这样的:

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

我想做的是按对象的“优先级”属性以降序排序。这部分已经完成,并且可以使用下面的代码。

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

到目前为止,一切都很好。现在,我想设置一个覆盖排序,将event_count> 4的所有项目放在最后一个位置。我什至不知道如何开始。最好我会在usort中同时做这两种逻辑。那有可能吗,我该怎么办?

谢谢

1 个答案:

答案 0 :(得分:0)

@deceze拥有此权利。您只需要在usort调用中添加逻辑即可。

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;
});

可能有更简洁的编写方式。但是这种方式使它很容易解释。