构建日期范围
我的开始日期为 20090101,结束日期为 20091130,我正在尝试构建和排列其间的所有月份,如下所示:
<?php
/* ... */
$arrDates['Jan'] = 2009;
$arrDates['Feb'] = 2009;
$arrDates['Mar'] = 2009;
/* ... */
?>
我该如何执行此操作?
I have a start date of 20090101 and an end date of 20091130 and I'm trying to build and array of all the months in between, which would look like this:
<?php
/* ... */
$arrDates['Jan'] = 2009;
$arrDates['Feb'] = 2009;
$arrDates['Mar'] = 2009;
/* ... */
?>
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我不完全理解你的数组结构。
但这也许有帮助:当使用 PHP 5.3 时,您可以使用如下代码来获取给定范围内所有月份的迭代器:
I don't fully understand your array structure.
But maybe this helps: When using PHP 5.3 you can use code like below to get an iterator with all months in the given range:
以下代码片段创建了这样一个数组:
但是,请注意,正如 danii 所评论的那样,您不清楚如何处理大于一年的时间跨度。上面的代码将仅使用您提供的范围内的最后一年。
该代码几乎适用于任何版本的 PHP(PHP 4+)。如果您想要更优雅的解决方案并且使用 PHP 5.2+,我推荐 GZipp 提供的解决方案。
The following snippet creates such an array:
However, note that, as danii commented, you are unclear about how you want to handle a timespan that is larger than a year. The code above will simply use the last year in the range you provide.
This code will work with pretty much any version of PHP (PHP 4+). If you want a more elegant solution and are using PHP 5.2+, I recommend the solution offered by GZipp.
我为旅行社建立的网站也遇到了类似的情况。您需要时间戳、数组和循环。看看PHP提供的日期函数。它为您提供了一些有趣的日期选择。例如,没有。指定月份中的天数。
I had a similar situation for a website i was building for travelagency. You need timestamps, arrays and looping. Take a look at the date function PHP provides. It gives you some interesting options to play with dates. E.g. the no. of days in a specified month.
您说“中间的月份”,但由于您的示例包括开始月份,我假设您的意思是“中间的月份加上开始和结束的月份”。
(这本质上是 johannes 的解决方案,通过一些手动阅读来使其适应 PHP 5.2。)
You say "the months in between", but since your example includes the starting month, I assume you mean "the months in between plus the starting and ending months".
(This is essentially johannes' solution with a little manual reading applied to adapt it for PHP 5.2.)
您不能使用月份作为键,键必须是唯一的,否则如果您的范围跨越一年以上,它将无法正常工作。
这将返回一个以 Mon-Year 为键的数组
You can't use the month as a key, the key must be unique or if your range spans more than a year it won't work correctly.
This will return an array with Mon-Year as the key
有点复杂但有效......:
A bit convoluted but works...: