我有这段代码:
$prod = "";
$vys = mysqli_query($db,"SELECT * FROM products ORDER BY name");
while ($arr = mysqli_fetch_assoc($vys)) {
$prod .= "<option value='".$arr['id_produktu']."'>".$arr['nazev']."</option>";
}
我希望有一个这个选项的数组,其中每个数组字段都是id_type之一。但我有点害怕在循环中使用循环:(技术上看起来像这样:
$prod = "";
$types = mysqli_query($db,"SELECT id_type FROM products");
while ($ts = mysqli_fetch_assoc($types)) {
$res = mysqli_query($db,"SELECT * FROM products WHERE id_type=$ts['id_type'] ORDER BY name");
while ($arr = mysqli_fetch_assoc($res)) {
$prod[$arr['id_type']] = "<option value='".$arr['id_produktu']."'>".$arr['nazev']."</option>";
}
}
所以我可以稍后根据id_type值调用(通过按下按钮值)一个确切的选项数组。 像这样(使用JS):
<script type=\"text/javascript\">
function setContent(divName, type){
var newdiv = document.createElement('div');
newdiv.innerHTML = \"<select name=idp[]>$prod[type]</select>\";
document.getElementById(divName).appendChild(newdiv);
}
你认为没有循环使用循环是可能的吗? ;)谢谢你:))
答案 0 :(得分:1)
似乎你只需要一个循环
$prod = array();
$res = mysqli_query($db,"SELECT * FROM products ORDER BY name");
while ($arr = mysqli_fetch_assoc($res))
{
if(!array_key_exists($arr['id_type'],$prod )
{
$prod[$arr['id_type']] =array();
}
$prod[$arr['id_type']][] = "<option value='".$arr['id_produktu']."'>".$arr['nazev']."</option>";
}
和
因为两个查询都在同一个表products
$types = mysqli_query($db,"SELECT id_type FROM products");
答案 1 :(得分:1)
$prod = array();
$vys = mysqli_query($db,"SELECT * FROM products ORDER BY name");
while ($arr = mysqli_fetch_assoc($vys)) {
$prod[$arr['id_type']][] = "<option value='".$arr['id_produktu']."'>".$arr['nazev']."</option>";
}
现在prod是一系列选项,包含你的产品。
稍后,要像使用字符串一样使用它,你需要将其内爆。
echo implode(' ', $prod['some type']);