2012-04-30 41 views
1

我正在PHP中構建一個日曆。每8個實例去新tr

在控制器中,我檢測到給定月份的天數,並將該範圍設置爲一個數組:daysInMonthArray

在視圖,然後我foreach這個陣列輸出每個數字爲<td>

<tr> 
    <?php 
    // output the number of days in the month 
     foreach($this->daysInMonthArray as $days1){ 
      foreach($days1 as $key => $object){ 
       echo "<td>" . $object . "</td>"; 
      } 
     } ?> 
</tr> 

我想開始一個新的<tr>每8個號,因爲有7天一個星期,需要開始一個新的行開始新的一週。

我試圖包圍該檢測到的輸出的剩餘部分,如果除以8如果輸出爲0,則新行,如果不是則進行if語句。但是,這沒有效果,因爲<tr>標籤超出了php語句。

如下回答和評論我已經更新了我的代碼:

<tr> 
     <?php 
     // output the number of days in the month 

     foreach($this->daysInMonthArray as $days1){ 
      foreach($days1 as $key => $object){ 
       if($object % 8 == 0){ 
        echo "</tr><tr><td>" . $object . "</td>"; 
       }else { 
       echo "<td>" . $object . "</td>"; 
       } 
      } 
     } ?> 
     </tr> 

這非常接近的作品,除了在一個月中間的兩個星期。它在中間2周放8天,而第一週和最後一週放7天。

+0

請參閱我試過的更新 – RSM

+0

您寫下「這沒有工作,因爲標籤超出了php語句」。所以你找到了問題所在。那麼把它們放入循環內怎麼樣? –

+0

我會嘗試一個增量變量,每7次迭代重置一次。此外,應該保留在循環之外的唯一標籤是表格標籤。 –

回答

1

你已經差不多這個自己回答下列要求:

這個沒有工作,因爲標籤是PHP語句外

你必須得到循環內的<tr>標籤。

<?php 
    $daysInRow = 0; 
    // output the number of days in the month 
    foreach($this->daysInMonthArray as $days1) 
    { 
     foreach($days1 as $key => $object) 
     { 
      if($daysInRow % 7 === 0) 
      { 
       echo '<tr>'; 
      } 

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

      if($daysInRow % 7 === 0) 
      { 
       echo '</tr>'; 
      } 

      if($daysInRow % 7 === 0) 
      { 
       $daysInRow = 0; 
      } 
      else 
      { 
       $daysInRow++; 
      } 
     } 
    } 
?> 

這是未經測試的代碼,可能更簡潔但希望您能明白。那你會碰上

+0

耶,模數師! :) –

+0

不幸這個輸出每個新號碼到一個新的tr。創造30行。查看有關更新的問題。 – RSM

0

一個概率是,你的嵌套表中現有的表。嘗試:

<tr><td> 
    <?php 
     // output the number of days in the month 
     foreach($this->daysInMonthArray as $days1){ 
     echo "<table>"; 

     $dayofweek = 0; 
     foreach($days1 as $key => $object){ 
      if($dayofweek%7 == 0) 
      echo "<tr>"; 

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

      if($dayofweek%7 == 0) 
      echo "</tr>"; 

      $dayofweek++;    
     } 

     if($dayofweek%7 != 0) //last tr 
      echo "</tr>"; 

     echo "</table>"; 
     } 
    ?> 
</td></tr>