【问题标题】:PHP Loop through months, starting in DecemberPHP 循环数月,从 12 月开始
【发布时间】:2014-05-05 16:51:07
【问题描述】:

我需要遍历 2012 年 12 月到 2017 年 11 月之间一年中的月份。所以开始月份是 12,结束月份是 11,开始年份是 2012 年,结束年份是 2017 年。

然后我查询一个日期格式为 2014-03-27 00:00:00 的数据库

我知道我大约在 4 年前做过这种事情,但现在似乎无法弄清楚。 这是我所拥有的:

$year_start = 2012;
$year_end = 2017;
$month_start = 12;
$month_end = 11;

$year = $year_start;
$month = $month_start;

$number_of_months = 3;

if ($month < 13 && $year < $year_end ) {

    $between_year_month = $year.'-'.$month;
    //echo $between_year_month;

    $query_total = "SELECT SUM(sales_points) FROM sales_list 
                    WHERE user_id ='".$_SESSION['users_id']."' 
                    AND sales_date BETWEEN '".$between_year_month."-01 00:00:00' AND '".$between_year_month."-30 23:59:59'";

    echo $query_total;

    $month++;

    if($month == 13) {
            $month = 1;
            $year = $year + 1;
    }

    $between_year_month = $year.'-'.$month;
    //echo $between_year_month;

}

非常感谢您的帮助。

【问题讨论】:

  • 我发布了 n 个答案,然后意识到我不知道您实际上遇到了什么问题。
  • 循环然后做什么?无论如何,您可以将数据库中的日期缩减为年份。

标签: php mysql date loops if-statement


【解决方案1】:

您最大的问题是您从未真正执行过您的查询。我还使用DateTime()DateInterval()DatePeriod() 简化了您的循环。

$start    = new DateTime('2012-12-01');
$end      = new DateTime('2017-11-01');
$interval = new DateInterval('P1M');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) { 
    $first_of_month = $dt->modify('first day of this month')->format('Y-m-d H:i:s');
    $end_of_month   = $dt->modify('last day of this month')->format('Y-m-d H:i:s');

    $query_total = "SELECT SUM(sales_points) FROM sales_list 
                WHERE user_id ='".$_SESSION['users_id']."' 
                AND sales_date BETWEEN '".$first_of_month ."' 
                AND '".$end_of_month   ."'";
    $result = mysqli_query($query_total, $conn);
    $row = mysqli_fetch_row($result);
    echo $row[0];
}

【讨论】:

  • 谢谢约翰,您的解决方案正是我所追求的。循环遍历具有开始和结束限制的日期。我将数据库 mysql_query 关闭,因为它最终与仅循环日期的问题无关。太棒了。
猜你喜欢
  • 1970-01-01
  • 2014-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多