0

我想知道是否有人可以帮助我。我想遍历一个关联数组并将结果放入两个组合框中。组合框将具有彼此完全相同的数据。

while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc))
{
    echo "<option value='" . $this->result['id] . "'>" 
               . $this->result['name'] . "</option>";
}

我是否必须为 2 个单独的组合框运行此循环两次,还是有更有效的方法来执行此操作?

4

3 回答 3

2

在这种情况下,您最好的选择是将文本累积在一个字符串中并回显两次。

$options = "";
while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc))
{
    $options.= "<option value='" . $this->result['id] . "'>" 
               . $this->result['name'] . "</option>";
}

echo "<select name='combo1'>".$options."</select>";
echo "<select name='combo2'>".$options."</select>";
于 2013-07-02T22:49:43.767 回答
0

像这样的东西怎么样(原始代码给你一个想法):

while
{
    $combo_options .= "<option>" ....// rest of your code
}

然后在您的选择中打印变量:

<select id="combo1"><?=$combo_options?></select>
<select id="combo2"><?=$combo_options?></select>
于 2013-07-02T22:48:22.193 回答
0

您可以将输出捕获为变量,然后根据需要回显它

while ($this->results = $this->dbhandle->fetch(PDO::FetchAssoc)){
     $output .= "<option value='" . $this->result['id'] . "'>" . $this->result['name'] . "</option>";
}

/// later on in your script

print $output;
于 2013-07-02T22:48:44.880 回答