2013-07-03 63 views
1

如何選擇最近的日期,而不是在一個PHP數組?選擇最近的日期,而不是PHP數組?

即假設我有一個數組

Array ([0] => 21/07/2013 [1] => 22/07/2013 [2] => 23/07/2013 [3] => 24/07/2013 [4] => 25/07/2013 [5] => 26/07/2013 [6] => 27/07/2013 [7] => 28/07/2013 [8] => 29/07/2013 [9] => 30/07/2013 [10] => 04/08/2013) 

和當前日期是20/07/2013。我需要檢查數組,並需要找到不在數組中的最近日期。即在這種情況下,日期21/07/2013 to 30/07/2013是在陣列和31/07/2013是最近的日期,我需要得到。

我怎麼能?

+1

你不能從一個甚至不在其中的數組中獲得值。告訴我們你想達到什麼目的,爲什麼,也許有更好的解決方案。 – Matheno

+0

「最近的日期」是什麼意思?數組中最後一個日期之後的日期? – Cos

+0

將所有日期轉換爲秒,對其進行排序並選擇大於當前日期的第一個日期,以秒爲單位 – Lixas

回答

2

如何使用簡單的while循環和DateTime類?

function getRecentDate(array $dates, $startDate) { 
    // Set up some utilities 
    $oneday = new DateInterval('P1D'); 
    $format = 'd/m/Y'; 

    // Build a DateTime object from the start date 
    $date = DateTime::createFromFormat($format, $startDate); 

    // Add one day and continue if date is in array 
    do { 
     $date->add($oneday); 
     $str = $date->format($format); 
    } while (in_array($str, $dates)); 

    // Return string representation of the date 
    return $str; 
} 

$dates = array('21/07/2013', '22/07/2013', '23/07/2013', '04/08/2013'); 
echo getRecentDate($dates, '20/07/2013'); // output: 24/07/2013 
+0

非常感謝你的兄弟...它的作品就像一個魅力......! –