Split an array of dates into consecutive date arrays

I have an array of dates that looks something like this:

Array ( [0] => 08/20/2013 [1] => 08/21/2013 [2] => 08/22/2013 [3] => 08/23/2013 [4] => 08/26/2013 ) 

it will always differ depending on the dates selected by the user, but, for example, allows you to use this one.

what I need to do is figure out a way to split the array into consecutive dates and non-consecutive dates.

so at the end I should have something like:

 Array ( [0] => 08/20/2013 [1] => 08/21/2013 [2] => 08/22/2013 [3] => 08/23/2013 ) Array ([4] => 08/26/2013) 

I must point out that these are not just two arrays. not consecutive dates will have their own array, but consecutive dates will be in their own array.

+4
source share
1 answer

Using $arr to represent your array:

 usort($arr, function ($a, $b){ return strtotime($a) - strtotime($b); }); $out = array(); $last = 0; $dex = -1; foreach ($arr as $key => $value){ $current = strtotime($value); if ($current - $last > 86400) $dex++; $out[$dex][] = $value; $last = $current; } print_r($out); 

Output:

 Array ( [0] => Array ( [0] => 08/20/2013 [1] => 08/21/2013 [2] => 08/22/2013 [3] => 08/23/2013 ) [1] => Array ( [0] => 08/26/2013 ) ) 
+3
source

Source: https://habr.com/ru/post/1497129/


All Articles