在 PHP5 中将当前日历周的日期作为数组返回
我将如何组合一个 PHP5 函数来查找当前日历周并将该周中每一天的日期作为数组返回,从星期一开始?例如,如果函数在今天(2010 年 2 月 25 日星期四)运行,则函数将返回如下数组:
How would I put together a PHP5 function that would find the current calendar week and return the dates of each day in the week as an array, starting on Monday? For example, if the function were run today (Thu Feb 25 2010), the function would return an array like:
[0] => Mon Feb 22 2010<br />
[1] => Tue Feb 23 2010<br />
[2] => Wed Feb 24 2010<br />
[3] => Thu Feb 25 2010<br />
[4] => Fri Feb 26 2010<br />
[5] => Sat Feb 27 2010<br />
[6] => Sun Feb 28 2010<br />
日期以什么格式存储在数组中并不重要,因为我认为这很容易更改.此外,最好能够选择提供日期作为参数并获取该日期的日历周而不是当前日历周.
It doesn't matter what format the dates are stored as in the array, as I assume that'd be very easy to change. Also, it'd be nice to optionally be able to supply a date as a parameter and get the calendar week of that date instead of the current one.
谢谢!
推荐答案
我想一个解决方案是从获取对应于上周一的时间戳开始,使用 strtotime
:
I suppose a solution would be to start by getting the timestamp that correspond to last monday, using strtotime
:
$timestampFirstDay = strtotime('last monday');
但是如果你今天尝试(thursday),像这样:
$timestampFirstDay = strtotime('last thursday');
var_dump(date('Y-m-d', $timestampFirstDay));
你会得到:
string '2010-02-18' (length=10)
即last week... 对于 strtotime,last" 表示 今天之前的那个".
i.e. last week... For strtotime, "last" means "the one before today".
这意味着您必须测试 "last monday" 是否是 strtotime
返回的加一星期,如果是,则加一星期...
Which mean you'll have to test if today is "last monday" as returned by strtotime
plus one week -- and, if so, add one week...
这是一个可能的(可能有更聪明的想法)解决方案:
Here's a possible (there are probably smarter ideas) solution :
$timestampFirstDay = strtotime('last monday');
if (date('Y-m-d', $timestampFirstDay) == date('Y-m-d', time() - 7*24*3600)) {
// we are that day... => add one week
$timestampFirstDay += 7 * 24 * 3600;
}
现在我们有了 "last monday" 的时间戳,我们可以编写一个简单的 for
循环,循环 7 次,每次增加 1 天,如下所示:
And now that we have the timestamp of "last monday", we can write a simple for
loop that loops 7 times, adding 1 day each time, like this :
$currentDay = $timestampFirstDay;
for ($i = 0 ; $i < 7 ; $i++) {
echo date('Y-m-d', $currentDay) . '<br />';
$currentDay += 24 * 3600;
}
这会给我们这样的输出:
Which will give us this kind of output :
2010-02-22
2010-02-23
2010-02-24
2010-02-25
2010-02-26
2010-02-27
2010-02-28
现在,由您决定:
Now, up to you to :
- 修改
for
循环,使其将日期存储在数组中 - 决定您要为
date
使用哪种格式 功能
- Modify that
for
loop so it stores the dates in an array - Decide which format you want to use for the
date
function
玩得开心;-)
相关文章