2013-06-01 51 views
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; 
} 
+0

這是不尋常的使用遞歸 – enrey

+0

@enrey的當涉及到日期總是不尋常的東西) ))) – Kin

回答

4

不要覺得太複雜;)根本沒有遞歸neeed。這將工作:

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 
+0

yap,但已經解決了它,但仍然感謝。 – Kin

相關問題