1

我需要获取自定义天数(例如 10 天),没有周日和周六可选。最后,我需要增加额外的一天而不是假期。所以我需要得到接下来的 10 天,节假日除外。问题是,当我添加额外的一天时,也可能是星期日或星期六,所以我对此使用了递归,而我只得到NULL.

public function getDates(){

    //~ How much days will be displayed
    $days_count = 10;
    //~ If saturday needed
    $saturday = FALSE; // TRUE / FALSE

    $end_date = new DateTime();
    $times = array();
    $times_extra = array();

    $end_date->add(new DateInterval('P'.$days_count.'D'));

    $period = new DatePeriod(
        new DateTime(),
        new DateInterval('P1D'),
        $end_date
    );

    foreach($period as $current_date){
        //~ Point result to default days by default
        $result =& $times;
        //~ Set internal date to current from the loop
        $date = $current_date;

        //~ if current date is sunday or saturday and it's is off
        if($current_date->format('N') == 7 || (!$saturday && $current_date->format('N') == 6)){
            //~ Point result to array of extra time, wich will be appended after the normal time
            $result = & $times_extra;
            //~ Get extra day
            $end_date = $this->getExtraDay($current_date, $end_date);
            //~ Set internal date to end date
            $date = $end_date;
        }

        //~ Save date
        array_push($result, array(
            'full_day' => $date->format('l'), 
            'date' => $date->format('Y-m-d')
            )
        );
    }

    $dates = array_merge($times, $times_extra);
}

private function getExtraDay($current_date, $end_date){
    if($current_date->format('N') == 6)
        $end_date->add(new DateInterval('P2D'));

    if($current_date->format('N') == 7)
        $end_date->add(new DateInterval('P1D'));

    if($end_date->format('N') == 6 || $end_date->format('N') == 7)
        $this->getExtraDay($current_date, $end_date);
    else
        return $end_date;
}
4

1 回答 1

4

不要想得太复杂;)根本不需要递归。这将起作用:

function getDates($days_count = 10, $saturday = FALSE) {
    $result = array();

    $current_date = new DateTime();
    $one_day = new DateInterval('P1D');

    while(count($result) < $days_count) {
        if($current_date->format('N') == 7 
        || (!$saturday && $current_date->format('N') == 6)) 
        {   
            $current_date->add($one_day);
            continue;    
        }   

        $result []= clone $current_date;
        $current_date->add($one_day);
    }   

    return $result;
}

这里有一个小测试:

foreach(getDates() as $date) {
    echo $date->format("D, M/d\n");
}

输出:

Mon, Jun/03
Tue, Jun/04
Wed, Jun/05
Thu, Jun/06
Fri, Jun/07
Mon, Jun/10
Tue, Jun/11
Wed, Jun/12
Thu, Jun/13
Fri, Jun/14
于 2013-06-01T09:44:46.400 回答