months '; ?> 效果很好并显示: 0 -6ren">
gpt4 book ai didi

php - 在选择选项中显示周数

转载 作者:行者123 更新时间:2023-11-28 00:13:08 26 4
gpt4 key购买 nike

我已经有了这样的选择选项:

<?php
echo 'Age : <select id="age" name ="age" class="selecta">';
for($i = 0; $i <= 24; $i += 0.25)
{
?>
<option value="<?php echo $i ;?>"
<?php
if ($_SESSION['age'] == $i)
{
echo " selected='selected'";
}
?> >
<?php echo $i .'&nbsp&nbsp' ?>
</option>
<?php
}
echo '</select> months <br />';
?>

效果很好并显示:

  0           // means 0 month
0.25 // means 1 week or 0.25 of month
0.50 // means 2 weeks or half month
0.75
1 // means 1 month
1.25
....
24

但它对用户来说看起来不太好。所以我想要的是让他们像这样:

0      // 0month
1 week
2 weeks
3 weeks
4 weeks
1 month
1 month and 1 week
1 month and 2 weeks
.....
24 months

完全一样并不是我最终的愿望,但我想要那样的东西。

这可能吗?

最佳答案

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>

关于php - 在选择选项中显示周数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13998487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com