我試圖創建一個遞歸函數以基於特定規則生成有效日期的數組。返回從某一特定日期的特定日期排除特定日期的日期排列,並排除某些日期
到目前爲止,我已經有了這個功能
function progDateRange($date, $end_date, $wkDays, $excluded, $dates = array())
{
$valid_date = false;
$max_date = new DateTime(date('Y-m-d'));
$max_date->add(new DateInterval('P2Y'));
$max_date = $max_date->format('Y-m-d');
// is this date before the end date or the max date
if(strtotime($date) <= strtotime($end_date) && strtotime($date) <= strtotime($max_date))
{
if(!in_array($date, $excluded))
{
foreach($wkDays as $day => $val)
{
// is this date a valid weekday start
if(date("l", strtotime($date)) == $day) {
// successful date
$valid_date = true;
}
}
if($valid_date) {
array_push($dates, $date);
}
}
$next_day = new DateTime($date);
$next_day->add(new DateInterval('P1D'));
progDateRange($next_day->format('Y-m-d'), $end_date, $wkDays, $excluded, $dates);
} else {
return $dates;
}
}
,我使用它像這樣一個單獨的頁面
$datesArray = progDateRange($date_start, $date_end, $wkDays, $excluded);
我傳遞一個開始日期,結束日期,上出現有效日期的星期幾陣列以及要排除的日期數組。
如果我print_r()
這樣
$next_day = new DateTime($date);
$next_day->add(new DateInterval('P1D'));
print_r($dates);
progDateRange($next_day->format('Y-m-d'), $end_date, $wkDays, $excluded, $dates);
每個循環並打印出數組函數內,並保持成功添加到它,但在單獨的頁面沒有某種原因,當我嘗試和print_r($datesArray)
獲取輸出不即使是一個空白數組,我根本無法弄清楚爲什麼。
我敢肯定,這將是一件愚蠢的事情,因爲該功能似乎大部分工作,它只是在返回數據的絆腳石。
我錯過了什麼?
我剛纔也試過在return語句前做一個print_r()
,這返回了我想要得到的確切數組。肯定有一些與返回腳麻/檢索調用函數的頁面上的數據...
編輯
由於我沒有提到它前面,這裏的$wkDays
例如VAR轉儲和$excluded
$wkDays
產生
array(6) {
[0]=>
string(6) "Monday"
[1]=>
string(7) "Tuesday"
[2]=>
string(9) "Wednesday"
[3]=>
string(8) "Thursday"
[4]=>
string(6) "Friday"
[5]=>
string(6) "Sunday"
}
和$excludes
可能是這樣的
array(23) {
[0]=>
string(10) "2013-04-22"
[1]=>
string(10) "2013-04-29"
[2]=>
string(10) "2013-05-13"
[3]=>
string(10) "2013-05-27"
[4]=>
string(10) "2013-06-03"
//...
}
一個示例調用可能會像這樣;
progDateRange("2013-05-01", "2017-05-01", array("Monday", "Wednesday"), array("2013-06-12", "2013-06-19"));
SOLUTION
採取千斤頂例子後,我不得不做一些調整,並結束了這一點;
function progDateRange($date, $end_date, $wkDays, $excluded)
{
$dates = array();
$todays_date = strtotime(date("Y-m-d"));
$current_date = strtotime($date);
$max_date = min(strtotime('+2 years'), strtotime($end_date));
while ($current_date < $max_date)
{
if (!in_array($date, $excluded) && in_array(date('l', $current_date), $wkDays) && $current_date > $todays_date) {
array_push($dates, $date);
}
$current_date = strtotime('+1 day', $current_date);
$date = date('Y-m-d', $current_date);
}
return $dates;
}
'$ MAX_DATE =日期( 'YM-d' 的strtotime('+ 2年))'看起來比你現在正在做的事情容易多了:)爲什麼遞歸? –