gpt4 book ai didi

php - 有什么方法可以在 php 中为十进制数运行 for 循环吗?

转载 作者:行者123 更新时间:2023-11-28 04:08:58 25 4
gpt4 key购买 nike

我需要使用 php FOR 循环显示带有十进制数字的选择框。见以下代码:

<select name="animationDelayTime">
<option value="0.1">0.1s</option>
<option value="0.2">0.2s</option>
<option value="0.3">0.3s</option>
<option value="0.4">0.4s</option>
<option value="0.5">0.5s</option>
<option value="0.6">0.6s</option>
<option value="0.7">0.7s</option>
<option value="0.8">0.8s</option>
<option value="0.9">0.9s</option>
<option value="1.0">1.0s</option>
<option value="1.1">1.1s</option>
<option value="1.2">1.2s</option>
<option value="1.3">1.3s</option>
</select>

这个循环会继续下去,直到到达第 10 个。

是否可以在 php 中循环十进制数?

If possible can anyone check following code that is not working. I fetch data from database and I used conditional statement for selecting and show existing record selected in select box:

<select class="form-control" name="delayTime" title="Choose animation delay time..." data-toggle="tooltip" required>
<?php
for ($x = 0.1; $x <= 10.1; $x=$x+0.1) {
if($x == $updateEntry->delayTime){
echo '<option value="' .$x.'" selected>'.$x.'s</option>';
}
echo '<option value="' .$x.'">'.$x.'s</option>'.PHP_EOL;
}
?>
</select>

Please see below screen shot. The value 7.1 should be selected in the select box but it not selected only beginning two or three number get selected, don't know why? Please help me to sort it. The value 7.1 should be selected in the select box but it not selected only beginning two or three number get selected, don't know why? Please help me to sort it.

最后我找到了在 foreach 循环中使用 range 来解决这个问题的方法。见下文:

<?php
foreach (range(0.1, 10, 0.1) as $val) {
$selected = ($val == $updateEntry->delayTime) ? "selected": "";
echo '<option value="' . $val . '" '.$selected.'>' . $val . 's</option>';
}
?>

最佳答案

您可以通过多种方式做到这一点。例如使用 for() 循环。从 0.1 开始,一直到 10 并且每一步递增 0.1

range() 也是一个不错的选择,但是您必须使用 foreach()

<?php
echo '<select name="animationDelayTime">';
for ($x = 0.1; $x <= 10; $x=$x+0.1) {
echo '<option value="' .$x.'">'.$x.'s</option>'.PHP_EOL;
}
echo '</select>';
?>

演示: https://3v4l.org/RlAcM

编辑:根据新的要求变更。这里我假设 $updateEntry->delayTime 的值为 0.5。您可以在从数据库中获取它时使用它。

<select class="form-control" name="delayTime" title="Choose animation delay time..." data-toggle="tooltip" required>
<?php
//$selected = '';
for ($x = 0.1; $x <= 10.1; $x=$x+0.1) {
$selected = ($x == 0.5) ? "selected": "";
echo '<option value="' .$x.'" '.$selected.'>'.$x.'s</option>'.PHP_EOL;
}
?>
</select>

关于php - 有什么方法可以在 php 中为十进制数运行 for 循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53248958/

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