使用PHP按给定的月份和年份获取一个月中每个星期的总天数


Get total day for every week in a month by given month and year using PHP

怎么做?

例如,看看这个2015年10月的日历

-  -  -  1  2  3  4    <---- 1st Week - TOTAL : 4 Days
5  6  7  8  9  10 11   <---- 2nd Week - TOTAL : 7 Days
12 13 14 15 16 17 18   <---- 3rd Week - TOTAL : 7 Days
19 20 21 22 23 24 25   <---- 4th Week - TOTAL : 7 Days
26 27 28 29 30 31 -    <---- 5th Week - TOTAL : 6 Days

现在我想把总共的4天,7天,7天等放在一个数组中,就像这样。

Array (
    [0] => Array
        ([TOTAL] => 4)
    [1] => Array
        ([TOTAL] => 7)
    [2] => Array
        ([TOTAL] => 7)
    [3] => Array
        ([TOTAL] => 7)
    [4] => Array
        ([TOTAL] => 6)
)

<?php
$date = '1-Oct-2015';
$date_timstamp = strtotime($date);
$day_in_month = date('t', $date_timstamp);
$arr_day_in_week = array();
$j=0;
for($i=0; $i<$day_in_month; $i++){
    $day = date('D', $date_timstamp);
    if($day == 'Sun'){
        $j++;
        $arr_day_in_week[] = $j;
        $j=0;
    }else{
        $j++;
    }
    $date_timstamp += 24*60*60;
}
if($j>0){
    $arr_day_in_week[] = $j;
}
print_r($arr_day_in_week);
?>

这个帖子可能很有用:https://codereview.stackexchange.com/questions/5451/is-this-a-good-algorithm-to-find-each-week-in-a-given-month

不确定它是否完全解决了你的问题,但它是一个很好的起点

通过修改harry的答案得到了它

$_TOTAL_DAY = cal_days_in_month(CAL_GREGORIAN,'10','2015');
$_COLLECT = array();
$SUM_WEEK = 0;
for($I=1; $I <= $_TOTAL_DAY; $I++){
    $LOOP_DATE = date($year.'-'.$month.'-'.$I);
    $LOOP_DAY = strtoupper(date('D',strtotime($LOOP_DATE)));
    if($LOOP_DAY == 'SUN'){
        $SUM_WEEK++;
        $_COLLECT[] = $SUM_WEEK;
        $SUM_WEEK = 0;
    } else{
        $SUM_WEEK++;
    }
}
if($SUM_WEEK>0){
    $_COLLECT[] = $SUM_WEEK;
}
print_r($_COLLECT);
die();

谢谢你