dongnao9525 2019-07-12 14:13
浏览 88
已采纳

如何按订单状态排序数组

I have an array with date, status and summ:

Array
(
    [0] => Array
        (
            [date] => 2019-07-06 14:01:52
            [status] => paid
            [summ] => 100

        )

    [1] => Array
        (
            [date] => 2019-07-02 12:22:31
            [summ] => 320
            [status] => pending
        )

    [2] => Array
        (
            [date] => 2019-07-01 18:43:58
            [summ] => 100
            [status] => pending
        )

    [3] => Array
        (
            [date] => 2019-06-26 14:01:52
            [status] => canceled
            [summ] => 200
        )

i need to sort this array by status first (1.pending, 2.paid, 3.canceled), and then by date (new at the top).

Order which i nedd:

pending 2019-07-02 12:22:31 pending 2019-07-01 18:43:58 paid 2019-07-06 14:01:52 canceled 2019-06-26 14:01:52

with date i don't have any problems:

usort($new11, function($a, $b) {
    return strtotime($b['date']) - strtotime($a['date']);
});

But how to sort by status in order which i need?

Thanx:)

  • 写回答

4条回答 默认 最新

  • dr5779 2019-07-12 14:40
    关注

    you can use Spaceship:

    <?php
    
        $new11 = [
            [
                'date' => '2019-07-06 14:01:52',
                'status' => 'paid',
                'summ' => 100,
            ],
            [
                'date' => '2019-07-02 12:22:31',
                'status' => 'pending',
                'summ' => 320,
            ],
            [
                'date' => '2019-07-01 18:43:58',
                'status' => 'pending',
                'summ' => 100,
            ],
            [
                'date' => '2019-06-26 14:01:52',
                'status' => 'canceled',
                'summ' => 200,
            ],
        ];
    
        $pending = 3;
        $paid = 2;
        $canceled = 1;
    
        usort($new11, function($a, $b) use ($pending, $paid, $canceled) {
            return (${$b['status']} <=> ${$a['status']}) * 10 +
                   (strtotime($b['date']) <=> strtotime($a['date']));
        });
    
    
        var_dump($new11);
    

    demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?