2016-06-22 118 views
0

我有一個列表的「代碼」和「組」。我需要能夠動態創建一個選擇框,其中使用optgroup對「代碼」進行分組。我試圖在網上嘗試一些解決方案,但沒有運氣。PHP mySQL選擇框與Optgroups

表信息:

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

應該在發帖前等了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>";