首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

从数组php中查找连续的日期时间

,可以通过以下步骤实现:

  1. 遍历数组,将日期时间字符串转换为时间戳,并存储在一个新的数组中。
  2. 对新数组进行排序,确保时间戳按照升序排列。
  3. 遍历排序后的数组,检查相邻的时间戳是否连续。如果连续,则将它们视为一个连续的日期时间段。
  4. 如果存在连续的日期时间段,记录下起始时间和结束时间,并将它们存储在一个结果数组中。
  5. 返回结果数组,其中包含所有连续的日期时间段。

以下是一个示例代码:

代码语言:txt
复制
function findContinuousDateTime($array) {
    $timestamps = array();
    foreach ($array as $datetime) {
        $timestamp = strtotime($datetime);
        if ($timestamp !== false) {
            $timestamps[] = $timestamp;
        }
    }
    
    sort($timestamps);
    
    $result = array();
    $start = null;
    $end = null;
    
    foreach ($timestamps as $timestamp) {
        if ($start === null) {
            $start = $timestamp;
            $end = $timestamp;
        } else {
            if ($timestamp - $end === 86400) { // 86400秒等于一天
                $end = $timestamp;
            } else {
                $result[] = array(
                    'start' => date('Y-m-d H:i:s', $start),
                    'end' => date('Y-m-d H:i:s', $end)
                );
                $start = $timestamp;
                $end = $timestamp;
            }
        }
    }
    
    if ($start !== null && $end !== null) {
        $result[] = array(
            'start' => date('Y-m-d H:i:s', $start),
            'end' => date('Y-m-d H:i:s', $end)
        );
    }
    
    return $result;
}

$array = array(
    '2022-01-01 12:00:00',
    '2022-01-02 12:00:00',
    '2022-01-03 12:00:00',
    '2022-01-05 12:00:00',
    '2022-01-06 12:00:00',
    '2022-01-07 12:00:00',
    '2022-01-09 12:00:00',
    '2022-01-10 12:00:00'
);

$result = findContinuousDateTime($array);

foreach ($result as $datetime) {
    echo "连续的日期时间段:{$datetime['start']} - {$datetime['end']}\n";
}

这段代码将输出以下结果:

代码语言:txt
复制
连续的日期时间段:2022-01-01 12:00:00 - 2022-01-03 12:00:00
连续的日期时间段:2022-01-05 12:00:00 - 2022-01-07 12:00:00
连续的日期时间段:2022-01-09 12:00:00 - 2022-01-10 12:00:00

在这个例子中,我们假设输入的数组中包含了一些日期时间字符串。代码首先将这些字符串转换为时间戳,并进行排序。然后,它遍历排序后的时间戳数组,检查相邻的时间戳是否连续。如果连续,则将它们视为一个连续的日期时间段,并记录下起始时间和结束时间。最后,代码返回一个结果数组,其中包含了所有连续的日期时间段。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券