使用数组填充下拉列表

时间:2017-11-09 04:29:04

标签: php html arrays drop-down-menu

我有一个选择Id e来用数组填充选项。我不知道怎么做。目前我正在尝试这个:

<html>
<head>
<title>test</title>
<body>
<select>
  <?php  $theArr = array("Home", "Events", "Bio", "Contact");?>
  <?php foreach ($theArr as $menu_option){ ?>
    <option><?php $menu_option; ?></option>
    <?php } ?>
</select>
</body>
</html>

但我得到的只是一个空的下拉,不知道我做错了什么

4 个答案:

答案 0 :(得分:1)

您需要为显示输出编写echo。将下拉列表更改为:

<select>
  <?php  $theArr = array("Home", "Events", "Bio", "Contact");?>
  <?php foreach ($theArr as $menu_option){ ?>
    <option><?php echo $menu_option; ?></option>
    <?php } ?>
</select>

答案 1 :(得分:0)

您没有输出任何内容

<html>
    <head>
    <title>test</title>
    </head> <!-- also close your head -->
    <body>
        <select>
            <?php  $theArr = array("Home", "Events", "Bio", "Contact");?>
            <?php foreach ($theArr as $menu_option){ ?>
            <option><?php echo $menu_option; ?></option>
            <?php } ?>
        </select>
    </body>
</html>

您需要在代码中添加echo,或print_r以确保正在打印结果。或者您只需使用<?=$menu_options;?>

即可

答案 2 :(得分:0)

您缺少echo语句

enter code here
<html>
<head>
 <title>test</title>
</head>
<body>
<select>
<?php  $theArr = array("Home", "Events", "Bio", "Contact");?>
<?php foreach ($theArr as $menu_option){ ?>
  <option><?php echo $menu_option; ?></option>
 <?php } ?>
</select>
</body>

答案 3 :(得分:0)

您错过了echo:)

<select>
    <?php  $theArr = array("Home", "Events", "Bio", "Contact");?>
    <?php foreach ($theArr as $menu_option): ?>
    <option><?php echo $menu_option; ?></option>
    <?php endforeach;?>
</select>

我还将您的{}更改为更容易阅读。