for($i = 0; $i <= 24; $i += 0.25) {
您在这里有一个 97 次迭代的序列。它同样是
range(0, 96);
然后,您将这些步骤中的任何一个映射到特定数字:
$map = function($step) {
return $step * 0.25;
}
例如,这将创建以下序列:
0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, ... , 23, 23.25, 23.5, 23.75, 24
所以现在你不想要这些数字,只想要美好的月份。如果您更轻松地采取步骤(而不是小数),则可以计算它们:
month: floor($step / 4) - division (integer)
weeks: $step % 4 - modulo (integer)
或者作为将其转换为文本的映射函数:
$map = function ($step) {
$month = floor($step / 4);
$week = $step % 4;
$buffer = '';
if ($month) {
$buffer .= "$month month";
}
if ($week) {
if ($month) {
$buffer .= ' and ';
}
$buffer .= "$week week" . ($week == 1 ? '' : 's');
}
return $buffer;
};
例如:
$map(0) # (empty)
$map(1) # 1 week
$map(10) # 2 month and 3 weeks
$map(95) # 23 month and 3 weeks
$map(96) # 24 month
因此,现在您只需将范围作为键映射到它们的值,然后您可以使用这些值执行选择框的标准输出:
$list = range(0, 96);
$selected = 12; // $_SESSION['age']
echo "Age : \n<select id='age' name ='age' class='selecta'>\n";
foreach ($list as $value)
{
$label = $map($value);
printf(" <option value='%d'%s>%s</option>\n", $value, $value === $selected ? " selected='selected'" : '', $label);
}
echo "</select>\n";
这为您提供了输出(Demo):
Age :
<select id='age' name ='age' class='selecta'>
<option value='0'></option>
<option value='1'>1 week</option>
<option value='2'>2 weeks</option>
<option value='3'>3 weeks</option>
<option value='4'>1 month</option>
...
<option value='11'>2 month and 3 weeks</option>
<option value='12' selected='selected'>3 month</option>
<option value='13'>3 month and 1 week</option>
...
<option value='50'>12 month and 2 weeks</option>
<option value='51'>12 month and 3 weeks</option>
<option value='52'>13 month</option>
<option value='53'>13 month and 1 week</option>
<option value='54'>13 month and 2 weeks</option>
...
<option value='92'>23 month</option>
<option value='93'>23 month and 1 week</option>
<option value='94'>23 month and 2 weeks</option>
<option value='95'>23 month and 3 weeks</option>
<option value='96'>24 month</option>
</select>