繁体   English   中英

PHP - 迭代db结果关联数组

[英]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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM