我尝试从当天开始接下来的6天存储,但是我很少会被困在这里如何在接下来的6天内存储$weekOfdays.是否有任何简单的功能可以做到这一点?
<?php
$weekOfdays = array();
$day = date('l');
$weekOfdays[] = $day;
$day = strtotime($day);
$next = strtotime("+6 day",$day);
$weekOfdays[] = date("l",$next);
var_dump($weekOfdays);
// output
// array (size=2)
// 0 => string 'Monday' (length=6)
// 1 => string 'Sunday' (length=6)
?>
Run Code Online (Sandbox Code Playgroud)
我想看到数组是这样的
array (size=7)
0 => string 'Monday' (length=6)
1 => string 'Tuesday' (length=7)
2 => string 'Wednesday' (length=9)
3 => string 'Thursday' (length=8)
4 => string 'Friday' (length=6)
5 => string 'Saturday' (length=8)
6 => string 'Sunday' (length=6)
Run Code Online (Sandbox Code Playgroud)
Nar*_*arf 15
这是一个不直接依靠自己进行数学运算的人:
$days = [];
$period = new DatePeriod(
new DateTime(), // Start date of the period
new DateInterval('P1D'), // Define the intervals as Periods of 1 Day
6 // Apply the interval 6 times on top of the starting date
);
foreach ($period as $day)
{
$days[] = $day->format('l');
}
下面提到了一些样本的方法很多:
1)在循环中使用strtotime函数和temp $date变量
$date = date('Y-m-d'); //today date
$weekOfdays = array();
for($i =1; $i <= 7; $i++){
$date = date('Y-m-d', strtotime('+1 day', strtotime($date)));
$weekOfdays[] = date('l : Y-m-d', strtotime($date));
}
print_r($weekOfdays);
Run Code Online (Sandbox Code Playgroud)
2)使用strtotime功能和+$i days当前日期
$date = date('Y-m-d'); //today date
$weekOfdays = array();
for($i =1; $i <= 7; $i++){
$weekOfdays[] = date('l : Y-m-d', strtotime("+$i day", strtotime($date)));
}
print_r($weekOfdays);
Run Code Online (Sandbox Code Playgroud)
3)使用DateTime类和modify方法
$date = date('Y-m-d'); //today date
$weekOfdays = array();
$date = new DateTime($date);
for($i=1; $i <= 7; $i++){
$date->modify('+1 day');
$weekOfdays[] = $date->format('l : Y-m-d');
}
print_r($weekOfdays);
Run Code Online (Sandbox Code Playgroud)
4)使用DateTime班级和DateInterval班级
$date = date('Y-m-d'); //today date
$weekOfdays = array();
$date = new DateTime($date);
for($i=1; $i <= 7; $i++){
$date->add(new DateInterval('P1D'));
$weekOfdays[] = $date->format('l : Y-m-d');
}
print_r($weekOfdays);
Run Code Online (Sandbox Code Playgroud)
5)使用DatePeriod,DateInterval和DateTime类
$date = date('Y-m-d', strtotime('+1 day')); //tomorrow date
$weekOfdays = array();
$begin = new DateTime($date);
$end = new DateTime($date);
$end = $end->add(new DateInterval('P7D'));
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $dt){
$weekOfdays[] = $dt->format('l : Y-m-d');
}
print_r($weekOfdays);
Run Code Online (Sandbox Code Playgroud)
今天是4月12日星期二,所以所有代码的输出将是:
Array
(
[0] => Wednesday : 2016-04-13
[1] => Thursday : 2016-04-14
[2] => Friday : 2016-04-15
[3] => Saturday : 2016-04-16
[4] => Sunday : 2016-04-17
[5] => Monday : 2016-04-18
[6] => Tuesday : 2016-04-19
)
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请查看: