在PHP5中将当前日历周的日期作为数组返回 [英] Return dates of current calendar week as array in PHP5

查看:106
本文介绍了在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.

谢谢! / p>

Thanks!

推荐答案

我想一个解决方案是从获得上一个星期一对应的时间戳开始,使用 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) em>,这样的东西:


But if you try with today (thursday), with something like this :

$timestampFirstDay = strtotime('last thursday');
var_dump(date('Y-m-d', $timestampFirstDay));

你会得到:

string '2010-02-18' (length=10)

即上周...对于strtotime,last表示今日之前

i.e. last week... For strtotime, "last" means "the one before today".

你必须测试如果今天是上一个星期,由 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,我们可以为循环编写一个简单的循环,循环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 :


  • 修改 循环,以便将日期存储在数组中

  • 决定要用于 date 功能

  • Modify that for loop so it stores the dates in an array
  • Decide which format you want to use for the date function

有乐趣; - )

这篇关于在PHP5中将当前日历周的日期作为数组返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆