dongxie3701 2014-05-07 17:31
浏览 87
已采纳

php在数组中找到3个连续日期

i have this code to find 3 consecutive dates in an array but i'm wondering if there is a better way to do this?

php code:

$datesarray = array('2012-10-01', '2012-10-03', '2012-10-04', '2012-10-05', '2012-10-08', '2012-10-09');

    $count = 0;
    $result = "Nothing found";

        foreach ($datesarray as $value) {
            if(strtotime($datesarray[$count]) - strtotime($datesarray[$count-1]) - strtotime($datesarray[$count-2]) == -1349150400) {
                $result = "3 Consecutive dates found";
            }
        $count++; 
        }  

    echo "Result: $result";
  • 写回答

1条回答 默认 最新

  • doutun1875 2014-05-07 17:55
    关注

    Your script gives me:

    Result: Nothing found
    

    but there are 3 consecutive dates

    I've changed the script:

    <?php
    
    $datesarray = array('2012-10-01', '2012-10-03', '2012-10-04', '2012-10-05', '2012-10-08', '2012-10-09');
    
    $result = "Nothing found";
    
    
    $diff = strtotime('2014-05-07') - strtotime('2014-05-06');
    
    for ($i=2, $c=count($datesarray); $i<$c; ++$i) {
        if (strtotime($datesarray[$i-1]) - strtotime($datesarray[$i-2]) == $diff &&
            strtotime($datesarray[$i]) - strtotime($datesarray[$i-2]) == $diff * 2) {
                $result = "3 Consecutive dates found";                
                break;
        }
    
    }
    echo "Result: $result";  
    

    and the result is

    Result: 3 Consecutive dates found
    

    Is this what you expected?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度