【问题标题】:Filtering and sorting Laravel collection过滤和排序 Laravel 集合
【发布时间】:2020-03-21 01:27:47
【问题描述】:

我有这个收藏:

    '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 中应该有所有订阅和任何重复的最早发送的通知。

【问题讨论】:

  • 看来你需要循环使用 sortBy('date') 并使用 shift() 获取元素
  • 那么到目前为止您尝试了哪些方法,遇到了什么错误?
  • 您的描述令人困惑。你首先给出一个例子,日期从 12 月开始,然后是 3 月,然后是 8 月。结果我看到一月,二月,三月。我几乎不明白你想要达到什么目的。你能写一个输入,然后是所需的输出。这个任务很简单,你只需要更具体。
  • @NikolayTraykov 第二个块只是一个块可以保存的示例,而不是结果,也许这还不够清楚,我会尝试重做它。

标签: laravel laravel-5 laravel-collection


【解决方案1】:

你为什么不试试用 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();
}

【讨论】:

    猜你喜欢
    • 2020-07-05
    • 2020-03-21
    • 2018-05-07
    • 2013-05-11
    • 2013-02-19
    • 2018-04-16
    • 1970-01-01
    • 2014-04-30
    • 2017-06-06
    相关资源
    最近更新 更多