根据php中的日期名称设置我的循环

时间:2017-07-20 05:22:37

标签: php html loops calendar html-table

我正在制作日历,并且我有一个自定义循环,其中包含数组中的所有日期名称,在任何特定月份的日期之后,我的循环将从1天开始到总天数。

<?php 
   $headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
  ?>


 <table border="1">

   <tr>
   <?php foreach($headings as $head){
     echo "<th>".$head."</th>";
 } ?>

  </tr>
 <tr>
 <?php  for($i=1;$i<=30;$i++){

   echo "<td>".$i."</td>";

    if($i%7 == 0){
      echo "</tr><tr>";
   }
}?>
</tr>
</table>

现在假设我的月份从星期五开始,那么我的Loop第一项从星期五开始。它目前从所有月份的星期日开始。任何帮助将受到高度赞赏。

3 个答案:

答案 0 :(得分:2)

这是您想要的解决方案。希望它会对你有所帮助。首先从一个月的每周开始。而且您还需要获得该特定月份的总天数。这里我举例说明当前的月份和年份。但你可以改变它

<?php 
   $headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
  ?>


 <table border="1">

   <tr>
   <?php foreach($headings as $head){
     echo "<th>".$head."</th>";
 } 
$for_month = date("m");
$for_year = date("Y");
/*$for_month = 02; //You can change this
$for_year = 2017;*/

$start_from =  date('w',strtotime(date("$for_year-$for_month-01")));
$total_days = cal_days_in_month(CAL_GREGORIAN,$for_month, $for_year);
 ?>

  </tr>
 <tr>
 <?php  for($i=1;$i<=($total_days+$start_from);$i++){
  if($i>$start_from)
   echo "<td>".($i-$start_from)."</td>";
 else
  echo "<td>"."&nbsp;"."</td>";

    if($i%7 == 0){
      echo "</tr><tr>";
   }
}?>
</tr>
</table>

答案 1 :(得分:1)

您可以使用基于偏移量的for循环

$offset = 3;

$count = count($headings );
for($i = $offset; $i < $count; $i++)
{
     echo $headings[$i]."<br />";
 }

答案 2 :(得分:1)

请阅读解释的评论

        <?php 
  $monthYear = "2017-07"; //get the month
  $fDate =  $monthYear."-01"; //get the starting month
  $sDate = 1; //statically start day
  $eDate = date("t", strtotime($fDate)); //get the last day of the month
   $headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
  ?>
 <table border="1">
   <tr>
   <?php
     for($x=0;$x<7;$x++){
        echo"<td>$headings[$x]</td>";
     }
    ?>
  </tr>
    <?php
    $z = 0;
    for($y=$sDate;$y<=$eDate;$y++){

        if($y < 10){
          //proper day initiator format
          $day = "0".$y;
          $date = $monthYear."-".$day; //build the date 
          $test = date("w", strtotime($date));
        } else {
          $day = $y;
          $date = $monthYear."-".$day; //build the date 
          $test = date("w", strtotime($date));
        }


        if($z == 0){
          //this is the initiator to get what day should the calendar start
          echo"<tr>";
          for($w=0; $w<$test; $w++){
            echo"<td></td>";
          }
          echo"<td>$day</td>";
          $z++;
        } else {
          echo"<td>$day</td>";
        }

        if($test == 6){
          //closer and new closer
          echo"</tr><tr>";
        }

        if($y == $eDate){
          //month closer
          echo"</tr>";
        }
     }
    ?>
</table>