2015-04-15 31 views
0

我試圖獲取每一年的日期或兩個日期之間的任何可變間隔。我的日期示例如下。它似乎永遠運行,我不能讓它工作,最終不會打印任何東西。php從現在開始每兩年的日期之間每隔1年獲取日期

$currentDate = '2014-04-15'; 
$endDate = '2018-04-15'; 
$reminder = '+1 year'; 

$dateArray = array(); 

    while($currentDate <= $endDate){ 
     $currentDate = date('Y-m-d', strtotime($reminder, strtotime($currentDate))); 
    array_push($dateArray, $currentDate); 
    } 
    print_r($dateArray); 

回答

0

請更改

$dateArray = array_push($dateArray, $currentDate); 

array_push($dateArray, $currentDate); 

因爲array_push,返回布爾和下一次,你調用這個函數,它會嘗試存儲字符串中的INT /布爾類型和導致錯誤。

+0

謝謝@Andriy是的,這是一個愚蠢的錯誤。我改變了它,但是它仍然沒有打印出任何結果。 –

+0

嘗試啓用錯誤輸出或查看日誌。我在在線測試中試過了你的代碼,並且它按預期工作。返回 Array([0] => 2015-04-15 [1] => 2016-04-15 [2] => 2017-04-15 [3] => 2018-04-15 [4] => 2019 -04-15) – Andriy

+0

真棒。謝謝@Andriy和所有幫助過我的人。它會出現我沒有迴應$ reminderP值。 –

0

您可以使用DateInterval類和DateTime :: add()方法:

$begin_date = DateTime::createFromFormat('Y-m-d', '2014-04-15'); 
    $end_date = DateTime::createFromFormat('Y-m-d', '2018-04-15'); 

    $res_array = array(); 

    while ($begin_date < $end_date) 
    { 
     $begin_date->Add(DateInterval::createFromDateString('1 year')); 
     $res_array[] = clone($begin_date); 
    } 
    echo ("<pre>"); print_r($res_array); echo ("</pre>"); 

多數民衆贊成在面向對象的風格。

相關問題