我试图创建一个递归函数以基于特定规则生成有效日期的数组。返回从某一特定日期的特定日期排除特定日期的日期排列,并排除某些日期
到目前为止,我已经有了这个功能
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年))'看起来比你现在正在做的事情容易多了:)为什么递归? –