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 に答える