我有一张包含"代码列表的表格#34;和"团体"。我需要能够使用"代码"动态创建一个选择框。使用optgroup分组。我曾尝试在网上搞乱一些解决方案,但没有运气。
表格信息:
CREATE TABLE `dtcodes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`groups` varchar(30) NOT NULL,
`code` varchar(5) NOT NULL,
`name` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=52 DEFAULT CHARSET=latin1
groups|codes|name
-----------------------
Materials|M1|No Product
Materials|M2|Low Brix
Other Equipment|AV1|Test1
Other Equipment|AV2|Test2
PHP mysqli:
$sqlcodes = "SELECT * FROM dtcodes ORDER BY groups ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
我最终的目标是这样的。
<select>
<optgroup label="Materials">
<option value="M1">No Product</option>
<option value="M2">Low Brix</option>
</optgroup>
<optgroup label="Other Equipment">
<option value="AV1">Test1</option>
<option value="AV2">Test2</option>
</optgroup>
答案 0 :(得分:1)
应该在发布之前等待20分钟才能解决这个问题。
echo "<td><select class='form-control'>";
echo "<option>Select a code...</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['groups']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['code'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";