简体   繁体   中英

split up an array of dates into consecutive date arrays

i have a 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's always going to be different depending on the dates the user selects but for example lets use this one.

what i need to do is figure out a way to separate the array into consecutive dates and non consecutive dates.

so in 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 should specify that it's not only two arrays. non consecutive dates would each have their own array, and consecutive dates would each be in their own array.

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
        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM