PHP-有没有一种简单的方法可以在两个日期之间循环并填写缺失的值? [英] PHP - Is there a simple way to loop between two dates and fill in missing values?

查看:99
本文介绍了PHP-有没有一种简单的方法可以在两个日期之间循环并填写缺失的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个约会.可以说他们看起来像这样.

I have 2 dates. Lets say they look like this.

$start = 2010/12/24;
$end = 2012/01/05;

我查询数据库以查找这两个日期之间的访问.我找到一些.然后,我填充一个名为stats的数组.

I query the database to look for visits between these two dates. I find some. I then populate an array called stats.

$stats['2010/12/25'] = 50;
$stats['2010/12/31'] = 25;
...

如您所见,还有很多天不见了. 我需要用零值填充缺失的日期.我在想这样的事情. (我已经从开始和结束日期中提取了日期/月份/年份.

As you can see, there are days missing. I need to fill the missing dates with a value of zero. I was thinking something like this. (I have pulled day / month / year from start and end dates.

for($y=$start_year; $y <= $end_year; $y++) {
    for($m=$start_month; $m <=$end_month; $m++) {
        for($d=$start_day; $d <= $end_day; $d++) {

这一年可以正常工作,但是几个月和几天都行不通.如果开始的日期是15日.随后的每个月的第1-14天都将丢失.那我可以有一个这样的解决方案...

This would work fine for the year however the months and days wouldn't work. If the start day is the 15th. Days 1-14 of each subsequent month would be missed. I could have a solution like this then...

for($y=$start_year; $y <= $end_year; $y++) {
    for($m=1; $m <13; $m++) {
         $total_days = cal_days_in_month(CAL_GREGORIAN, $m, $y) + 1;
         for($d=1; $d <= $total_days; $d++) {

然后,我需要一堆if语句,以确保开始和结束的月份和日期有效.

I would then need a bunch of if statements making sure starting and end months and days are valid.

是否有更好的方法?还是可以在我的mysql查询中完成?

Is there a better way of doing this? Or could this even be done in my mysql query?

推荐答案

只是演示了一些PHP更新的间隔处理方法(由pgl在他的回答中提到)的功能:

Just to demonstrate the power of some of PHP's newer interval handling method (mentioned by pgl in his answer):

$startDate = DateTime::createFromFormat("Y/m/d","2010/12/24",new DateTimeZone("Europe/London"));
$endDate = DateTime::createFromFormat("Y/m/d","2012/01/05",new DateTimeZone("Europe/London"));

$periodInterval = new DateInterval( "P1D" ); // 1-day, though can be more sophisticated rule
$period = new DatePeriod( $startDate, $periodInterval, $endDate );

foreach($period as $date){
   echo $date->format("Y-m-d") , PHP_EOL;
}

需要PHP> = 5.3.0

Does require PHP >= 5.3.0

编辑

如果需要包括实际的结束日期,则需要在foreach()循环之前立即在$ endDate中添加一天:

If you need to include the actual end date, then you need to add a day to $endDate immediately before the foreach() loop:

$endDate->add( $periodInterval );

编辑#2

$startDate = new DateTime("2010/12/24",new DateTimeZone("Europe/London"));
$endDate = new DateTime("2012/01/05",new DateTimeZone("Europe/London"));

do {
   echo $startDate->format("Y-m-d") , PHP_EOL;
   $startDate->modify("+1 day");
} while ($startDate <= $endDate);

对于PHP 5.2.0(或更早的版本,如果启用了dateTime对象)

For PHP 5.2.0 (or earlier if dateTime objects are enabled)

这篇关于PHP-有没有一种简单的方法可以在两个日期之间循环并填写缺失的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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