dsfdsf21312 2017-08-01 21:57
浏览 52
已采纳

如何使用数组顺序对此Collection进行排序?

How can I sort the $item type based on the order? This is what I currently have:

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

Basically it's a two column sort where it first sorts by type and then sorts by date. The type would be sorted using the array order rather than the typical alphabetical order.

  • 写回答

1条回答 默认 最新

  • donglun1020 2017-08-01 22:43
    关注

    You could compare the keys in $order corresponding to the type of each item.

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

    This should work if all of your items have types contained in $order. If not, you'll get undefined index errors which will mess up the sort. But since you haven't specified how items like that should be sorted in your question, I'm assuming that they all do.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?