5

過去 10 年間と次の 10 年間の値を SELECT ボックスに入力するこの PHP コードがあります。

<select name="fromYear"';
   $starting_year  =date('Y', strtotime('-10 year'));
   $ending_year = date('Y', strtotime('+10 year'));

    for($starting_year; $starting_year <= $ending_year; $starting_year++) {
 echo '<option value="'.$starting_year.'">'.$starting_year.'</option>';
  }             
 echo '<select>

現在の年を自動的に選択するにはどうすればよいですか?

4

8 に答える 8

4
<?php
//get the current year
$Startyear=date('Y');
$endYear=$Startyear-10;

// set start and end year range i.e the start year
$yearArray = range($Startyear,$endYear);
?>
<!-- here you displaying the dropdown list -->
<select name="year">
    <option value="">Select Year</option>
    <?php
    foreach ($yearArray as $year) {
        // this allows you to select a particular year
        $selected = ($year == $Startyear) ? 'selected' : '';
        echo '<option '.$selected.' value="'.$year.'">'.$year.'</option>';
    }
    ?>
</select>
于 2016-02-02T12:09:39.437 に答える
0

選択した属性を使用する必要があります

$starting_year  =date('Y', strtotime('-10 year'));
$ending_year = date('Y', strtotime('+10 year'));
for($starting_year; $starting_year <= $ending_year; $starting_year++) {
   if(date('Y')==$starting_year) { //is the loop currently processing this year?
      $selected='selected'; //if so, save the word "selected" into a variable
   } else {  
      $selected='' ; //otherwise, ensure the variable is empty
   }
   //then include the variable inside the option element
   echo '<option '.$selected.' value="'.$starting_year.'">'.$starting_year.'</option>';
}
于 2013-06-26T12:45:31.793 に答える
0
for($starting_year; $starting_year <= $ending_year; $starting_year++) {
    if($starting_year == date('Y')){
        echo '<option selected=selected value="'.$starting_year.'">'.$starting_year.'</option>';
    }else{
        echo '<option value="'.$starting_year.'">'.$starting_year.'</option>';
    }
}

あなたの代わりに上記の for ループのコードを使用してください。

于 2013-06-26T12:44:31.583 に答える
0
echo '<select name="fromYear">';
$cur_year = date('Y');
for($year = ($cur_year-10); $year <= ($cur_year+10); $year++) {
    if ($year == $cur_year) {
        echo '<option value="'.$year.'" selected="selected">'.$year.'</option>';
    } else {
        echo '<option value="'.$year.'">'.$year.'</option>';
    }
}               
echo '<select>';
于 2013-06-26T12:44:47.290 に答える