2013-10-22 39 views
2

我使用下面的語法來填充週週期的下拉框。範圍從3個月前到1年。如何將PHP生成的日期範圍默認爲當前星期

<select id="period" name="period" onchange="updateperioddiv();" class="tekwani-input-select"> 

     <?php 
      for($i = 0; $i <= 445; $i ++){ 

      $startdate = strtotime("today + $i day - 90 day"); 
      $enddate = strtotime("today + " . ($i + 6) . " day - 90 day "); 

      if(date('D', $startdate) == 'Mon'){ 

       echo '<option'.' value="'. date('Y-m-d', $startdate) . ' ">' .date('d M y', $startdate) . " to " . date('d M y', $enddate) . "</option>"; 
      } 
      } 
     ?> 
    </select> 

所以這默認爲3個月前,我怎麼能得到它有默認選擇爲當前周?

PHP fiddel here

感謝,

回答

1

的strtotime()返回的Unix時間戳,其表示爲數字,你可以因此做簡單的邏輯上的值進行比較,以確定是否今天是一個特別的一週內。

// Get unix time of today 
$today = strtotime("today"); 

for($i = 0; $i <= 445; $i ++){ 

    $startdate = strtotime("today + $i day - 90 day"); 
    $enddate = strtotime("today + " . ($i + 6) . " day - 90 day "); 

    if(date('D', $startdate) == 'Mon'){ 

     echo '<option '; 
     // check to see if today is inside this week 
     if($startdate < $today && $enddate > $today){ 
      echo ' selected="selected"'; 
     } 

     echo ' value="'. date('Y-m-d', $startdate) . ' ">' .date('d M y', $startdate) . " to " . date('d M y', $enddate) . "</option>"; 

    } 
} 
+0

謝謝請問,這樣的邏輯。謝謝 :-) – JustStarting

0

你可以嘗試喜歡這個 -

<select id="period" name="period" onchange="updateperioddiv();" class="tekwani-input-select"> 

     <?php 
      echo "week".date("Y",$startdate); 
      for($i = 0; $i <= 445; $i ++){ 

      $startdate = strtotime("today + $i day - 90 day"); 
      $enddate = strtotime("today + " . ($i + 6) . " day - 90 day "); 

      if(date('D', $startdate) == 'Mon'){ 
       $selected = ""; 
       if(date('W', $startdate) == date('W')) 
        $selected = "selected"; 
       echo '<option'.' value="'. date('Y-m-d', $startdate) . ' " $selected>' .date('d M y', $startdate) . " to " . date('d M y', $enddate) . "</option>"; 
      } 
      } 
     ?> 
    </select> 
相關問題