PHP-通过数据库结果关联数组进行迭代


PHP - Iterating through db result associative array

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

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

我必须为两个单独的组合框运行两次这个循环吗?或者有更有效的方法吗?

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

$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>";

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

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

然后打印您选择的变量:

<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;