2017-02-27 120 views
0

我想从日期数组中获得未来的第一个日期。我试图写我自己的功能,但没有完成任务。获取将来的最近日期

private static function getClosestDate($date, array $dates, $last) { 
    $interval    = array(); 
    $now     = strtotime(date('Y-m-d')); 

    foreach ($dates as $d) { 
     $dateTime   = strtotime($date); 
     $toTime    = strtotime($d); 

     // Do not parse dates older than today 
     if (strtotime($d) < $now) { continue 1; } 

     // Only do dates in the future 
     if ($toTime < $dateTime) { continue 1; } 
     $interval[]   = abs($dateTime - $toTime); 
    } 

    // If there is no interval, use the latest date 
    if (!count($interval)) { 
     return $last; 
    } 

    asort($interval); 
    $closest    = key($interval); 
    return $dates[$closest]; 
} 

此代码的工作原理,但它也适用于其他方式。接下来,当没有最后一个日期时,它应该使用最后一个日期的$ last参数。

我想知道这个的原因是因为我有一个日期范围,人们可以预订夜间。我想知道天数的差异来计算他们可以预订的夜晚的数量。计算日期的差异很容易,但我确实需要知道下一次预订何时出现。这些在$日期参数中提供。

我应该在我的代码更改为得到它固定的(我试图继续在foreach每当日期是在过去的基础上,$ date参数),或有人可以提供我的代码?

+0

你为什么要通过引用传递'$ dates'?你不要修改它在你的函数中的任何地方。 –

+0

我试着删除使用日期,这会导致问题。我遗漏了参考。 –

+0

只是一个小提示:不要将日期作为文本处理,这使得数学很难做到。 –

回答

0

我自己解决了这个问题。现在,我不再使用日期数组,而是使用日期作为间隔中的键,以再次检索日期。这确实工作正常。

private static function getClosestDate($date, array $dates, $last) { 
    $interval    = array(); 
    $now     = strtotime(date('Y-m-d')); 

    foreach ($dates as $d) { 
     $dateTime   = strtotime($date); 
     $toTime    = strtotime($d); 

     // Do not parse dates older than today 
     if (strtotime($d) < $now) { continue 1; } 

     // Only do dates in the future 
     if ($toTime < $dateTime) { continue 1; } 
     $interval[$d]  = abs($dateTime - $toTime); 
    } 

    // If there is no interval, use the latest date 
    if (!count($interval)) { 
     return $last; 
    } 

    asort($interval); 
    $closest    = key($interval); 

    return $closest; 
}