OurBG
OurBG

Reputation: 597

Filtering and sorting Laravel collection

I have this 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'
        ]
    ]
]

There's a lot of subscriptions.

The items inside are notifications. There could be 1 to 4 UNIQUE notifications and each one could repeat twice, i.e. up to 8 records.

So a single subscription could look like that:

       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

I want to order each Subscription's notifications by date and then extract ALL first notifications in a $first collection, all second notifications in $second collection and so on up to fourth.

So in $first there should be the earliest sent notification for all subscriptions and any duplicates.

Upvotes: 0

Views: 233

Answers (1)

Murat Tutumlu
Murat Tutumlu

Reputation: 780

Why don't you try a loop with 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();
}

Upvotes: 0

Related Questions