php如何生成一年的日历表_使用php动态生成一个日历,附源码。【简单实用】
日歷在web開發中是非常常用的一個功能,網上搜也能找到一大堆日歷組件,大部分是js組件。
因為再開發過程中需要使用到日歷的功能,又不想下載什么日歷組件。所以就自己動手寫了一個簡單的php生成日歷的功能。
源碼如下:
/*
* @動態生成一個日歷
* @param 日期[2016-07-01|2017-02-01]
* @return table
*/
function create_calendar($month){
#初始化
$calendar = '';
#表頭
$week_arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
#本月共多少天
$this_month_days = (int)date('t',strtotime($month));
#本月1號星期幾
$this_month_one_n = (int)date('w', strtotime($month));
//表頭
$calendar .= '
foreach ($week_arr as $k => $v){
if($k == 0){
$class = ' class="sunday"';
}elseif ($k == 6){
$class = ' class="saturday"';
}else{
$class = '';
}
$calendar .= '
'.$v.'';}
$calendar .= '
';//表身
#計算本月共幾行數據
$total_rows = ceil(($this_month_days - (7 - $this_month_one_n)) / 7) + 1;
$number = 1;
$flag = 0;
for ($row = 1;$row <= $total_rows;$row++){
$calendar .= '
';for ($week = 0;$week <= 6;$week ++){
if($number < 10){
$numbera = '0'.$number;
}else{
$numbera = $number;
}
if(date('Ym',strtotime($month)) .$numbera == intval(date('Ymd'))){
$cell_id = ' id="today"';
}else{
$cell_id = '';
}
if($number <= $this_month_days){
if($row == 1){
if($week >= $this_month_one_n){
$calendar .= '
'.$number.'';$flag = 1;
}else{
$calendar .= '
';}
}else{
$calendar .= '
'.$number.'';}
if($flag){
$number ++;
}
}else{
$calendar .= '
';}
}
$calendar .= '
';}
$calendar .= '
';return $calendar;
}
id=today的就是今天的日期。
使用方法
參數直接傳一個日期,date類型的。如要用17年2月份的日歷,則參數傳2017-02-01;如果要17年1月的則傳參數2017-01-01。
$calendar = create_calendar('2017-02-01');
echo $calendar;
結果如下
樣式的話需要自己手動寫一下,或者直接使用bootstrap。具體效果可以參考本站的簽到日歷。非常簡單有用的小函數。
總結
以上是生活随笔為你收集整理的php如何生成一年的日历表_使用php动态生成一个日历,附源码。【简单实用】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: XCP概念和基本原理介绍
- 下一篇: 调侃我的大小