0

我有一个动态下拉菜单,显示数字 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
4

2 回答 2

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>';
于 2012-11-23T01:48:59.153 回答
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>";
  }
}
于 2012-11-23T01:47:33.460 回答