PHP For循环重复数组

时间:2018-06-11 09:19:23

标签: php arrays loops for-loop calendar

我正在尝试创建一个日历系统,该系统将显示特定日期预订的作业,我希望它是一个水平日历,其中包含所有日期的月份作为表格行和日期本周作为下一行。我已经对第一行进行了排序,但是我需要让第二行重复一周中的数组,直到月末结束。

      //Establish How many days are in the current Month
  $currentMonthDays = date("t");




  $daysOfWeek = array('M','T','W','T','F','Sa','Su');

      echo '<table cellpadding="0" cellspacing="0" border="1" bordercolor="ffffff">
            <tr>';


                    for ($i = 1; $i <= $currentMonthDays; $i++)
                    {

                        echo '<td width="30" align="center">'.$i.'</td>';
                    }

      echo '</tr><tr>';


                    foreach($daysOfWeek as $day){
                    echo '<td width="30" align="center">'.$day.'</td>';
                    }


      echo '</tr>';

3 个答案:

答案 0 :(得分:1)

试试这个:

 //Establish How many days are in the current Month
  $currentMonthDays = date("t");
  $daysOfWeek = array('M','T','W','T','F','Sa','Su');
      for ($i = 0; $i <= $currentMonthDays-1; $i++){
          $arrayWeekDays[] = $daysOfWeek[($i%7)];
      }
      echo '<table cellpadding="0" cellspacing="0" border="1" bordercolor="ffffff">
            <tr>';


                    for ($i = 1; $i <= $currentMonthDays; $i++)
                    {

                        echo '<td width="30" align="center">'.$i.'</td>';
                    }

      echo '</tr><tr>';


                    foreach($arrayWeekDays as $day){
                    echo '<td width="30" align="center">'.$day.'</td>';
                    }


      echo '</tr>';

干杯:)

答案 1 :(得分:0)

尝试以下代码

    $currentMonthDays = date("t");

    $daysOfWeek = array('M', 'T', 'W', 'T', 'F', 'Sa', 'Su');

    echo '<table cellpadding="0" cellspacing="0" border="1" bordercolor="ffffff">
        <tr>';

    for ($i = 1; $i <= $currentMonthDays; $i++) {

        if ($i % 7 == 1) 
            echo '</tr><tr>';
        echo '<td width="30" align="center">' . $i . '</td>';
    }

    echo '</tr><tr>';


    foreach ($daysOfWeek as $day) {
            echo '<td width="30" align="center">' . $day . '</td>';
    }


    echo '</tr>';

也许可以帮到你。

答案 2 :(得分:0)

最简单的方法是使用DateTime类和格式化方法来获取为您设置日期格式的天数。

$currentMonthDays = date('t');
$month = date('m');
$year = date( 'Y');

for ($i = 1; $i <= $currentMonthDays; $i++) {
    echo '<td width="30" align="center">'.$i.'</td>';
}
$day = new DateTime();
for ($i = 1; $i <= $currentMonthDays; $i++) {
    $day->setDate( $year, $month, $currentMonthDays);
    // this outputs first 3 letters of day, but you can truncate if you want..
    echo '<td width="30" align="center">'.$day->format('D').'</td>';
}

您还可以通过合并两个td并通过在月份的某天和星期几之间添加br元素来格式化单元格来避免需要2个循环,或者使用CSS格式。