设置不同的选项并获取它们的值

Setting up different options and getting their values

我正在使用以下代码向我的页面添加各种 select 元素。但是,由于我在 while 循环中执行此操作,所以所有元素的值都是相同的

function options($pos, $count) {

    for ($i = 0; $i < $count; $i++) {
        $options = '';

        $STH = //code to get data from db

        $STH->execute();

        while($row2 = $STH->fetch()) {
            $options .="<option>" . $row2['name'] . "</option>";
        }

        $menu= "<select name='filter' id='filter'>
            " . $options . "
            </select>";

        echo $menu;
    }

}

然后我需要在用户按下按钮后获取每个 select 元素的值。但是由于每个 select 元素的名称都是相同的,所以我不知道该怎么做。有什么办法解决这个问题吗?

例如,如果计数为 5,将创建五个单独的下拉列表(即使每个下拉列表中的选项相同)。然后用户选择与他相关的选项并按下提交按钮。然后我需要获取他从下拉菜单中选择的值,但我不知道该怎么做,因为所有下拉菜单的名称都是相同的

你应该这样做:

<select name='filter' id='filter'>
  <?php 
     while($row2 = $STH->fetch()) {
            $options .="<option>" . $row2['name'] . "</option>";
     } ?>
</select>";

假设您有许多 select 个带有动态选项的标签

解决方案是让 select 标签的名称不同(动态)

<form method="POST">
<?php
cust_options(5);
function cust_options($count) {
    for ($i = 0; $i < $count; $i++) {
        $options = '';
        $j = 1;
        while($j < 4) {
            $options .="<option>" . 'option'.$j . "</option>";
            $j++;
        }
        $ind = $i+1;
        $temp = 'filter_'.$ind;
        $menu= "<select name='$temp'>
            " . $options . "
            </select>";

        echo $menu;
    }

}
?>
<input type="submit">
<?php print_r($_POST); ?>
</form>