PHP-遍历db结果关联数组

PHP-遍历db结果关联数组,php,Php,我想知道是否有人能帮我。我想遍历一个关联数组,并将结果放入两个组合框中。组合框中的数据彼此完全相同 while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc)) { echo "<option value='" . $this->result['id] . "'>" . $this->result['name'] . "</option&g

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

while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc))
{
    echo "<option value='" . $this->result['id] . "'>" 
               . $this->result['name'] . "</option>";
}
while($this->results=$this->dbhandle->fetch(PDO::fetch_Assoc))
{
回显“结果['name']。”;
}

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

类似的方法如何(原始代码让您了解):

while
{
$combo_options.=''..//代码的其余部分
}
然后将变量打印在您的选择中:

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

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

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;
while($this->results=$this->dbhandle->fetch(PDO::FetchAssoc)){
$output.=''.$this->result['name']。'';
}
///稍后在脚本中
打印$输出;

在这种情况下,最好的办法是将文本累积成一个字符串并回显两次

$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>";
$options=”“;
而($this->results=$this->dbhandle->fetch(PDO::fetch_Assoc))
{
$options.=“结果['name']”;
}
回显“$options.”;
回显“$options.”;

使用一个收集变量,而不是回显HTML。我想你的意思是每次都附加到$output而不是覆盖。谢谢,我觉得我应该自己考虑一下。我感谢大家的反应。
$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>";