Select records with consecutive dates

  laravel, laravel-collection, php, php-carbon

In a laravel collection how can I select only items with consecutive dates? Here is my collection:

array [
  0 => array [
    "id" => 271
    "user_id" => 914
    "date" => "2019-09-05T08:00:00.000000Z"
  ]
  1 => array [
    "id" => 272
    "user_id" => 916
    "date" => "2019-09-10T08:00:00.000000Z"
  ]
  2 => array [
    "id" => 273
    "user_id" => 914
    "date" => "2019-09-09T08:00:00.000000Z"
  ]
  3 => array [
    "id" => 274
    "user_id" => 914
    "date" => "2019-09-10T08:00:00.000000Z"
  ]
  4 => array [
    "id" => 275
    "user_id" => 900
    "date" => "2019-09-09T08:00:00.000000Z"
  ]
  5 => array [
    "id" => 274
    "user_id" => 914
    "date" => "2019-08-24T08:00:00.000000Z"
  ]
  6 => array [
    "id" => 275
    "user_id" => 914
    "date" => "2019-08-25T08:00:00.000000Z"
  ]
]

The date field is cast as a Carbon object. I want to select any items where the dates are consecutive weekdays (so a Friday and Monday would be consecutive), grouped by user. So for the data above I would like to return:

0 => array [
  5 => array [
    "id" => 274
    "user_id" => 914
    "date" => "2019-08-24T08:00:00.000000Z"
  ]
  6 => array [
    "id" => 275
    "user_id" => 914
    "date" => "2019-08-25T08:00:00.000000Z"
  ]
]

1 => array [
  2 => array [
    "id" => 273
    "user_id" => 914
    "date" => "2019-09-09T08:00:00.000000Z"
  ]
  3 => array [
    "id" => 274
    "user_id" => 914
    "date" => "2019-09-10T08:00:00.000000Z"
  ]
]

The real-life dataset has 100,000s of entries, so I’m trying to find an efficient way of doing this.

Source: Laravel

Leave a Reply