2017-02-27 119 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; 
}