2011-01-30 113 views
0

我有一個事件日曆的開始和結束日期如下:需要通過開始 - 結束日期循環幫助

16.08.2010 12:00:00 - 21.08.2010 20:00:00
16.08.2010 20:00:00 - 21.08.2010 23:00:00
18.08.2010 17:00:00 - 18.08.2010 19:00:00

每當一個事件去在一天之內,我需要循環每一天。

我發現這個線程,我想到的是能幫助我:How to find the dates between two specified date?

我不能使用PHP 5.3的解決方案,因爲我的服務器上運行PHP 5.2。
其他解決方案不產生輸出。

這是我嘗試做:

$events = $data['events']; 

foreach($ev as $e) : 

    $startDate = date("Y-m-d",strtotime($e->startTime)); 
    $endDate = date("Y-m-d",strtotime($e->endTime)); 

    for($current = $startDate; $current <= $endDate; $current += 86400) { 
     echo '<div>'.$current.' - '.$endDate.' - '.$e->name.'</div>'; 
    } 
endforeach; 

從理論上講,這應該遍歷所有天延伸數天的事件。 但這沒有發生。

的邏輯是錯誤的地方....請幫助:)

回答

2

的問題是,你要號碼添加到字符串。 date('Y-m-d')產生一個像2011-01-31這樣的字符串。向它添加數字將不起作用[如預期]:'2011-01-31' + 86400 = ?

嘗試一些沿着這些路線:

// setting to end of final day to avoid glitches in end times 
$endDate = strtotime(date('Y-m-d 23:59:59', strtotime($e->endTime))); 
$current = strtotime($e->startTime); 

while ($current <= $endDate) { 
    printf('<div>%s - %s - %s</div>', date('Y-m-d', $current), date('Y-m-d', $endDate), $e->name); 
    $current = strtotime('+1 day', $current); 
} 
+0

現貨!謝謝:) – Steven 2011-01-31 00:18:58

0

日期( 「Y-M-d」)是錯誤的,你需要在for循環的strtotime結果。嘗試這個,它應該工作:

$events = array(
    array('16.08.2010 12:00:00', '21.08.2010 20:00:00', 'event1'), 
    array('16.08.2010 20:00:00', '21.08.2010 23:00:00', 'event2'), 
    array('18.08.2010 17:00:00', '18.08.2010 19:00:00', 'event3'), 
); 

$dayLength = 86400; 
foreach($events as $e) : 

    $startDate = strtotime($e[0]); 
    $endDate = strtotime($e[1]); 

    if(($startDate+$dayLength)>=$endDate) continue; 

    for($current = $startDate; $current <= $endDate; $current += $dayLength) { 
     echo '<div>'.date('Y-m-d', $current).' - '.date('Y-m-d', $endDate).' - '.$e[2].'</div>'; 
    } 

endforeach; 
+0

好吧,我還不夠快...... :) – Marc 2011-01-31 00:23:42