我需要获得自定义天数(例如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 :(得分: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