PHP - 迭代db结果关联数组

时间:2013-07-02 22:45:19

标签: php

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

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

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

3 个答案:

答案 0 :(得分: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>";

答案 1 :(得分:0)

这样的事情(给你一个想法的原始代码):

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

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

<select id="combo1"><?=$combo_options?></select>
<select id="combo2"><?=$combo_options?></select>

答案 2 :(得分: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;