0

好的,我在这里有一个逻辑问题而不是编码一个,但是代码示例/解决方案可能会同时回答这两个问题,所以这里......

如果我有一个表格,我用 start_date 和 end_date 传入 PHP (在 m/d/Y 格式上是完整的),我需要打印出 mysql 数据库中属于该范围的所有条目的表(所以从 m1/d1/ Y1 到 m2/d2/Y2) 按月分组,我怎么能以一种优雅的方式去做呢?

例如,如果我通过 start_date = 5/20/2012, end_date = 7/31/2012,我需要结果表以这种格式显示结果:

May 2012  |  June 2012  |  July 2012
....      |  ....       |  .....

2012 年 5 月的第一列将显示 mysql 查询的结果,例如

SELECT ... WHERE signup_date >= 5/20/2012 AND signup_date <= 5/31/2012

2012 年 6 月同样显示:

SELECT ... WHERE signup_date >= 6/1/2012 AND signup_date <= 6/30/2012

ETC

因此,我正在寻找一种方法将开始日期和结束日期解析为从该月的开始日期到该月的最后一天正确排列的日期数组,如果 end_date 是几个月后,则涵盖所有其他日期完全介于两者之间的月份(从该月的第一天到最后一个月),以便我可以在 for/while 循环中循环它们?所以像:

[0]['开始'] =​​> '5/20/2012'

[0]['结束'] => '5/31/2012'

[1]['开始'] =​​> '6/1/2012'

[1]['结束'] => '2012 年 6 月 30 日'

[2]['开始'] =​​> '7/1/2012'

[2]['结束'] => '7/31/2012'

有任何想法吗?

4

3 回答 3

0

您应该使用mktime()来实现这一点。下面的示例代码。

<?php
$startDate = '05/20/2012';
$endDate = '07/31/2012';


$curMonth =  date("m", strtotime($endDate)); //End Month
$curYear = date("Y", strtotime($endDate)); //End Year

$months = array();
$months[] = array('start' => "$curMonth/01/$curYear", 'end' => $endDate);

while ("$curMonth/01/$curYear" > $startDate) {
        $monthEnd =  date("m/d/Y", mktime(0, 0, 0, $curMonth, 0, $curYear));
        $curMonth = date('m', strtotime($monthEnd));
        $curYear = date('Y', strtotime($monthEnd));
        $monthStart = ($curMonth/01/$curYear > $startDate) ? $startDate : "$curMonth/01/$curYear";
        $months[] = array('start' => $monthStart, 'end' => $monthEnd);
}

print_r(($months));
?>
于 2012-11-02T15:27:00.900 回答
0

尝试这个:

$date = '5/20/2012';
$dateStart = date("m/01/y", strtotime($date));

$start = date("Y-m-d", strtotime($dateStart));
$end = date("Y-m-d", strtotime($dateStart. '+ 1 month - 1 day') );

echo $start;
echo $end;
于 2012-11-02T04:45:18.650 回答
-1

请先查看我的评论以了解 mysql db 日期格式。

用伪语言写了一点

     $sql="SELECT * FROM ... WHERE `signup_date`>='2012-5-20' AND `signup_date`<'2012-5-31' ORDER BY  `signup_date`";


        $result=mysql_query($sql);

    $month_year=array() //3-dimensional array $month_year[year][month][primary_key];

    $month_index=-1;
    while($row=mysql_fetch_assoc($result)){

    // find $month_of_the_date AND $year_of_the_date

    //find different months ,corresponding years, and db primary key and keep track in the $month_year array




    }

    for( all the years in the array ){

    for(all the corresponding months of the year  in the array){

//**EDIT:** you MIGHT need other loops and arrays to collect distinct years and corresponding months together

    // show the records with the primary keys corresponding to that month and year



    }




    }
于 2012-11-02T04:45:44.073 回答