如何在动态下拉菜单中插入以下这些值

时间:2012-11-23 01:40:41

标签: php html

我有一个动态下拉菜单,显示数字1- 10的每个值:

$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$durationHTML = '';
$durationHTML .= '<select name="duration" id="durationDrop">'.PHP_EOL; 
$durationHTML .= '<option value="">Please Select</option>'.PHP_EOL;  
foreach ($years as $year) {
    $durationHTML .= "<option>$year</option>".PHP_EOL;  // if no value attribute, value will be whatever is inside option tag, in this case, $year
}
$durationHTML .= '</select>';

我想要做的是更改值,以便在下面显示以下值:

1
1/2
2
2/3
3
3/4
4
4/5
5
5/6
6
6/7
7
7/8
8
8/9
9
9/10
10

我的问题是如何在上面动态显示这些值?

更新

$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$durationHTML = '';
$durationHTML .= '<select name="duration" id="durationDrop">'.PHP_EOL; 
$durationHTML .= '<option value="">Please Select</option>'.PHP_EOL;  

for($i = 0; $i < sizeof($years); $i++)
{
  $current_year = $years[$i];
  $durationHTML .= "<option>{$current_year}</option";
  if($i != (sizeof($years) - 1 )) //So you don't try to grab 11 because it doesn't exist.
  {
    $next_year = $years[$i+1];
    $durationHTML .= "<option>{$current_year}/{$next_year}</option>";
  }
}

$durationHTML .= '</select>'; 

以下是输出内容:

11/2
22/3
33/4
44/5
55/6
66/7
77/8
88/9
99/10
10

2 个答案:

答案 0 :(得分:1)

这样的事情对你有用;

$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$durationHTML = '';
$durationHTML .= '<select name="duration" id="durationDrop">'.PHP_EOL; 
$durationHTML .= '<option value="">Please Select</option>'.PHP_EOL;  
foreach ($years as $year) {
    $durationHTML .= "<option>$year</option>".PHP_EOL;  
    if ($year != $max_year) {
         $nextYear = $year + 1;
         $durationHTML .= "<option>$year / $nextYear</option>".PHP_EOL;              
    }
}
$durationHTML .= '</select>';

答案 1 :(得分:0)

你可能有几种方法可以做到这一点。

最简单的方法是将foreach循环更改为简单的for循环,并获取下一个值并使用它来形成分数。我这样做是为了更容易阅读,但你不需要将current_year和next_year存储在变量中,你可以直接从数组中回显它们。

for($i = 0; $i < sizeof($years); $i++)
{
  $current_year = $years[$i];
  echo "<option>{$current_year}</option";
  if($i != (sizeof($years) - 1 )) //So you don't try to grab 11 because it doesn't exist.
  {
    $next_year = $years[$i+1];
    echo "<option>{$current_year}/{$next_year}</option>";
  }
}