从 for 循环创建 PHP 下拉菜单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20177788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:57:37  来源:igfitidea点击:

Create a PHP Dropdown menu from a for loop?

phphtmlformsloops

提问by user3010383

I am trying to create a drop down menu with the options of 1,2,3 and 4.

我正在尝试创建一个带有 1、2、3 和 4 选项的下拉菜单。

The below code is what I am using just now and the dropdown is empty.

下面的代码是我刚刚使用的,下拉列表是空的。

Any idea what I am doing wrong?

知道我做错了什么吗?

<select name="years">
<?php 

for($i=1; $i<=4; $i++)
{

"<option value=".$i.">".$i."</option>";
}
?> 
     <option name="years"> </option>   
        </select> 

            <input type="submit" name="submitYears" value="Year" />

回答by sudee

You are not outputting the option tags. Try it like this:

您没有输出选项标签。像这样尝试:

<select name="years">

<?php 

for($i=1; $i<=4; $i++)
{

    echo "<option value=".$i.">".$i."</option>";
}
?> 
     <option name="years"> </option>   
</select> 

<input type="submit" name="submitYears" value="Year" />

回答by SpiderLinked

You basically use html without closing the php syntax.Your code should look like this:

您基本上使用 html 而不关闭 php 语法。您的代码应如下所示:

 <select name="years">
    <?php 

    for($i=1; $i<=4; $i++)
     {
      ?>

     <option value="<?php echo $i;?>"><?php echo $i;?></option>
    <?php
        }
        ?> 
 <option name="years"> </option>   
    </select> 

        <input type="submit" name="submitYears" value="Year" />

Or are you trying to echo the option? In that case you forgot the echo statement:

或者你想回应这个选项?在这种情况下,您忘记了 echo 语句:

 echo "<option value= ".$i.">".$i."</option>"; 

回答by jade290

This worked for me. It populates years as integers from the current year down to 1901:

这对我有用。它将年份填充为从当前年份到 1901 年的整数:

        <select Name='ddlSelectYear'>
            <option value="">--- Select ---</option>

            <?php
            for ($x=date("Y"); $x>1900; $x--)
              {
                echo'<option value="'.$x.'">'.$x.'</option>'; 
              } 
            ?> 
        </select>

回答by hasnath rumman

<select name="year">
    <?php for ($i = 0; $i <= 9; $i++) : ?>
         <option value='<?= $i; ?>' <?= $fetchData->year == $i ? 'selected' : '' ?>><?= $i; ?></option>
    <?php endfor; ?>
</select>

回答by MeNa

You forgot something..

你忘记了什么。。

Add print/ echobefore "<option value=".$i.">".$i."</option>";

添加print/echo之前"<option value=".$i.">".$i."</option>";

回答by wapper20

place an echo in your loop to output your options.

在循环中放置一个 echo 以输出您的选项。

echo "<option value=".$i.">".$i."</option>";

回答by Harshal Mahajan

Just echo the <option>tag

只需回显<option>标签

echo "<option value=".$i.">".$i."</option>";