将日期数组划分为连续的块 [英] Dividing an Array of Dates Into Contiguous Blocks

查看:116
本文介绍了将日期数组划分为连续的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

检查集合内的连续日期并按范围返回

我有一个从mySQL查询获得的日期数组。我需要将数组分成多个数组,以便每个数组中的日期是连续的。

I have an array of dates which is obtained from a mySQL query. I need to divide the array into multiple arrays so that the dates in each array are contiguous.

因此,如果我以

$datearray = array("2013-05-05", "2013-05-06", "2013-05-07", "2013-05-08", "2013-06-19", "2013-06-20", "2013-06-21");

我需要能够将其拆分为

$firstdatearray = array("2013-05-05", "2013-05-06", "2013-05-07", "2013-05-08");
$seconddatearray = array("2013-06-29", "2013-06-30", "2013-07-01");

最后我将能够打印


3月5日至8月29日-7月1日

5 - 8 Mar, 29 Jun - 1 Jul

我该怎么做?我不知道从哪里开始。

How can I do that? I haven't a clue where to start.

推荐答案

这是一个完整的工作答案。 (享受!)

您必须遍历$ datearray中的每个值

You'll have to loop through each value in $datearray

<?php

$datearray = array("2013-05-05", "2013-05-06", "2013-05-07", "2013-05-08", "2013-06-19", "2013-06-20", "2013-06-21");
asort($datearray);
$resultArray = array();
$index = -1;
$last = 0;
$out = "";

foreach ($datearray as $date) {
    $ts = strtotime($date);
    if (false !== $ts) {
        $diff = $ts - $last;

        if ($diff > 86400) {
            $index = $index + 1;
            $resultArray[$index][] = $date;
        } elseif ($diff > 0) {
            $resultArray[$index][] = $date;
        } else {
            // Error! dates are not in order from small to large
        }
        $last = $ts;
    }
}

foreach ($resultArray as $a) {
    if (count($a) > 1) {
        $firstDate = $a[0];
        $firstDateBits = explode('-',$firstDate);
        $lastDate = $a[count($a)-1];
        $lastDateBits = explode('-',$lastDate);

        if ($firstDateBits[1] === $lastDateBits[1]) {
            $out .= intval($firstDateBits[2]) . '-' . intval($lastDateBits[2]) . ' ' . date("M",strtotime($firstDate)) . ', ';  
        } else {
            $out .= date("M d",strtotime($firstDate)) . '-' . date("M d",strtotime($lastDate)) . ', ';  
        }
    }
}

这是输出:

5-8 May, 19-21 Jun

这篇关于将日期数组划分为连续的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆