关键词搜索

源码搜索 ×
×

php算法 计算时间段的最大连续天数

发布2020-10-14浏览555次

详情内容

需求:需要计算这个时间数组的最大连续天数,9号到11号有连续三天,但是12号断开了,15号到18是一个连续的四天,所以计算结果应该是最大连续天数是 4 天.

/**
     * 求出最大连续天数
     */
    if (!function_exists("continue_days")){
        function continue_days($time_array=null){
            $list_length = count($time_array);
            $continue_days = 1;
 
            $continue_days_array = [];
 
            for($i = 0;$i < $list_length;$i++){
                $today = strtotime($time_array[$i]);
                if($i == $list_length -1){
                    $continue_days_array[] = $continue_days;
                }else{
                    $yesterday = strtotime($time_array[$i + 1]);
                    $one_day = 24 * 3600;
                    if($today - $yesterday == $one_day){
                        $continue_days += 1;
                    }else{
                        $continue_days_array[] = $continue_days;
                        $continue_days = 1;
                    }
                }
            }
            if (count($continue_days_array) > 0){
                $max_days = max($continue_days_array);
            }else{
                $max_days = 0;
            }
            return $max_days;
//            var_dump($continue_days_array);
        }
    }

    使用示例:

    $router->get('/', function () use ($router) {
     
        $dates = [
            '2018-10-09',
            '2018-10-10',
            '2018-10-11',
            '2018-10-13',
            '2018-10-15',
            '2018-10-16',
            '2018-10-17',
            '2018-10-18',
        ];
     
        dd(continue_days(array_reverse($dates)));
     
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    输出结果:
    echo 4

    相关技术文章

    点击QQ咨询
    开通会员
    返回顶部
    ×
    微信扫码支付
    微信扫码支付
    确定支付下载
    请使用微信描二维码支付
    ×

    提示信息

    ×

    选择支付方式

    • 微信支付
    • 支付宝付款
    确定支付下载