简体   繁体   中英

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

How to do that?

For example look at this October 2015 calendar

-  -  -  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

Now i want to get those total 4 Days, 7 Days, 7 Days,etc in an array so its just like this.

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

Thanks in advance.

<?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);

?>

This post might be good use : https://codereview.stackexchange.com/questions/5451/is-this-a-good-algorithm-to-find-each-week-in-a-given-month

Not sure it has the full solution to your problem but it's a good starting point imo

Got it..by modifying harry answer

$_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();

thank you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM