过滤和排序Laravel集合

时间:2020-03-21 01:27:47

标签: laravel laravel-5 laravel-collection

我有这个收藏集:

    'subscription_1' => [
        [
            'name' => 'test',
            'date' => '2020-12-10'
        ],
        [ 
            'name' => 'another test'
            'date' => '2020-12-10'
        ],
        [ 
            'name' => 'another test'
            'date' => '2020-12-11'
        ],
        [ 
            'name' => 'another test'
            'date' => '2020-12-11'
        ]
    ],
    'subscription_5' => [
        [
            'name' => 'test',
            'date' => '2020-03-04'
        ],
        [ 
            'name' => 'another test'
            'date' => '2020-03-04'
        ],
        [ 
            'name' => 'another test'
            'date' => '2020-08-06'
        ],
        [ 
            'name' => 'another test'
            'date' => '2020-08-06'
        ]
    ]
]

有很多订阅。

里面的项目是通知。可能有1到4个UNIQUE通知,每个通知可以重复两次,即最多8条记录。

因此,单个订阅可能如下所示:

       Notification 2020-08-06 15:13:05
       Notification 2020-08-06 15:13:05
       Notification 2020-09-04 12:05:03
       Notification 2020-09-04 12:05:03
       Notification 2020-10-05 14:03:05
       Notification 2020-10-05 14:03:05

我想按日期对每个订阅的通知进行排序,然后提取$first集合中的所有第一条通知,$second集合中的所有第二条通知,以此类推,直到第四条。

因此,在$first中,应该为所有订阅和所有重复项发送最早的通知。

1 个答案:

答案 0 :(得分:0)

为什么不尝试用collect()循环:

foreach($notifications as $id => $notification) {
    $sorted = collect($notification)->sortBy('date');
    $first[$id] = $sorted->shift();
    $second[$id] = $sorted->shift();
    $third[$id] = $sorted->shift();
    $fourth[$id] = $sorted->shift();
}