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.

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

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器