2013-07-02 31 views
0

我想知道是否有人可以帮助我。我想遍历一个关联数组,并将结果放到两个组合框中。组合框将具有完全相同的数据。PHP - 通过db结果关联数组遍历

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

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

+0

使用收集变量而不是回显HTML。 –

回答

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>"; 
+0

谢谢,我觉得我应该自己想到这一点。我感谢大家的回应。 – Ralph

0

如何像这样(原始代码给你一个想法):

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

然后打印您的选择里面的变量:

<select id="combo1"><?=$combo_options?></select> 
<select id="combo2"><?=$combo_options?></select> 
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; 
+1

认为你的意思是追加到$输出,而不是每次覆盖 – Orangepill