PHP開發之製作簡單日曆計算日曆的天數與樣式

113.png

自訂函數caculate方法,計算日曆的天數與樣式。

1)將上個月的天數計算出來,本月第一天的星期不是星期天的話,就需要根據上個月的最後一天計算

2)將本月的天數遍歷出來,如果是休息天就加上特殊的css樣式

3)將下個月的天數計算出來,分三種情況,星期日、星期六和工作日

<?php
function caculate($calendar) {   //$calendar 通过threshold方法计算后的数据
    $days = $calendar['days'];
    $firstDayOfWeek = $calendar['firstDayOfWeek'];//本月第一天的星期
    $lastDayOfWeek = $calendar['lastDayOfWeek'];//本月最后一天的星期
    $lastMonthOfLastDay = $calendar['lastMonthOfLastDay'];//上个月的最后一天
    $year = $calendar['year'];
    $month = $calendar['month'];
    $dates = array();
    
   if($firstDayOfWeek != 7) {
      $lastDays = array();
      $current = $lastMonthOfLastDay;//上个月的最后一天
      for ($i = 0; $i < $firstDayOfWeek; $i++) {
         array_push($lastDays, $current);//添加上一个月的日期天数
         $current--;
      }
      $lastDays = array_reverse($lastDays);//反序
      foreach ($lastDays as $index => $day) {
         array_push($dates, array('day' => $day, 'tdclass' => ($index ==0 ?'rest':''), 'pclass' => 'outter'));
      }
   }
   
   //本月日历信息
   for ($i = 1; $i <= $days; $i++) {
      $isRest = $this->_checkIsRest($year, $month, $i);
      //判断是否是休息天
      array_push($dates, array('day' => $i, 'tdclass' => ($isRest ?'rest':''), 'pclass' => ''));
   }
   
   //下月日历信息
   if($lastDayOfWeek == 7) {//最后一天是星期日
      $length = 6;
   }
   elseif($lastDayOfWeek == 6) {//最后一天是星期六
      $length = 0;
   }else {
      $length = 6 - $lastDayOfWeek;
   }
   for ($i = 1; $i <= $length; $i++) {
      array_push($dates, array('day' => $i, 'tdclass' => ($i==$length ?'rest':''), 'pclass' => 'outter'));
   }
   
   return $dates;
}
?>

註:

array_push() 函數在第一個參數的陣列尾部新增一個或多個元素,然後傳回新陣列的長度。

array_reverse() 函數傳回翻轉順序的陣列。

繼續學習
||
<?php function caculate($calendar) { //$calendar 通过threshold方法计算后的数据 $days = $calendar['days']; $firstDayOfWeek = $calendar['firstDayOfWeek'];//本月第一天的星期 $lastDayOfWeek = $calendar['lastDayOfWeek'];//本月最后一天的星期 $lastMonthOfLastDay = $calendar['lastMonthOfLastDay'];//上个月的最后一天 $year = $calendar['year']; $month = $calendar['month']; $dates = array(); if($firstDayOfWeek != 7) { $lastDays = array(); $current = $lastMonthOfLastDay;//上个月的最后一天 for ($i = 0; $i < $firstDayOfWeek; $i++) { array_push($lastDays, $current);//添加上一个月的日期天数 $current--; } $lastDays = array_reverse($lastDays);//反序 foreach ($lastDays as $index => $day) { array_push($dates, array('day' => $day, 'tdclass' => ($index ==0 ?'rest':''), 'pclass' => 'outter')); } } //本月日历信息 for ($i = 1; $i <= $days; $i++) { $isRest = $this->_checkIsRest($year, $month, $i); //判断是否是休息天 array_push($dates, array('day' => $i, 'tdclass' => ($isRest ?'rest':''), 'pclass' => '')); } //下月日历信息 if($lastDayOfWeek == 7) {//最后一天是星期日 $length = 6; } elseif($lastDayOfWeek == 6) {//最后一天是星期六 $length = 0; }else { $length = 6 - $lastDayOfWeek; } for ($i = 1; $i <= $length; $i++) { array_push($dates, array('day' => $i, 'tdclass' => ($i==$length ?'rest':''), 'pclass' => 'outter')); } return $dates; } ?>
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!