获取每年所有周

获取指定年第一周到最后一周的日期分布。当年则截取到当日所在周。用于时间分类数据统计。

function get_week($year)
{
    $year_start = $year . "-01-01";
    $year_end = $year . "-12-31";
    $startday = strtotime($year_start);
    if (intval(date('N', $startday)) != '1') {
        $startday = strtotime("next monday", strtotime($year_start)); //获取年第一周的日期
    }
    $year_mondy = date("Y-m-d", $startday); //获取年第一周的日期
 
    $endday = strtotime($year_end);
    if (intval(date('W', $endday)) == '7') {
        $endday = strtotime("last sunday", strtotime($year_end));
    }
 
    //如果是当前年则统计到当前周
    $now_year = date('Y');
    if ($now_year == $year) {
        $num = date('W', strtotime(date('Y-m-d')));
    }  else {
        $num = intval(date('W', $endday));
        if ($num == '1'){
            $num = intval(date('W',$endday -(7*24*3600)))+1;
        }
    }

    for ($i = 1; $i <= $num; $i++) {
        $j = $i -1;
        $start_date = date("Y-m-d", strtotime("$year_mondy $j week "));
        $end_day = date("Y-m-d", strtotime("$start_date +6 day"));
        if (!(date("Y",strtotime("$year_mondy $j week ")) > $year)){
            $week_array[$i] = array(
                substr(str_replace("-", ".", $start_date), 5),
                substr(str_replace("-", ".", $end_day), 5));
        }
    }
    return $week_array;
}