【问题标题】:How can I sort this Collection using an array order?如何使用数组顺序对该集合进行排序?
【发布时间】:2017-08-01 21:57:26
【问题描述】:

如何根据订单对 $item 类型进行排序?这是我目前拥有的:

$order = ['AA', 'zl', 'Dr', 'co', 'og'];

$items->sort(
    function ($a, $b) use ($order) {
        return strcmp($b->type, $a->type) // how do I apply the order here?
            ?: strcmp($b->date, $a->date);
    }
);

基本上这是一个两列排序,首先按类型排序,然后按日期排序。该类型将使用数组顺序而不是典型的字母顺序进行排序。

【问题讨论】:

    标签: php laravel collections


    【解决方案1】:

    你可以比较$order中的key对应每个item的类型。

        return ($order[$b->type] - $order[$a->type]) 
               ?: strcmp($b->date, $a->date);
    

    如果您的所有项目的类型都包含在$order 中,这应该可以工作。如果没有,你会得到未定义的索引错误,这会弄乱排序。但是由于您没有指定在您的问题中应该如何对此类项目进行排序,我假设它们都这样做。

    【讨论】:

    • 完美运行。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 2011-03-30
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    相关资源
    最近更新 更多