我有一个用PHP构建的选项组。一切都很好,直到我必须得到DetailID的值而不是DetailName来查找记录。我仍然需要显示DetailName而不是DetailID,我需要将DetailID添加到此。我该怎么做?
<?php
include("config.php");
$sql = "SELECT DetailType AS type, DetailID, GROUP_CONCAT(DISTINCT DetailName
ORDER BY DetailName ASC
SEPARATOR '|') AS DetailName FROM tblDetails GROUP BY DetailType";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<optgroup label='{$row['type']}'>";
$DetailNames = explode('|', $row['DetailName']);
foreach($DetailNames as $DetailName) {
echo '<option value='.$DetailID.'>'.$DetailName.'</option>';
}
echo "</optgroup>";
}
?>
表。 tblLocDet 位置ID 1,1,2,3 DetailID 1,2,3,4
tblDetails DetailType特征,膳食期,服务,类型 DetailID 1,2,3,4 DetailName自助餐,壁炉,WiFi,海滨
答案 0 :(得分:2)
这有效......
$sql = "SELECT DISTINCT DetailType AS type, DetailID, DetailName FROM tblDetails
ORDER BY DetailType, DetailName";
$result = mysql_query($sql) or die(mysql_error());
$prev='';
while ($row = mysql_fetch_assoc($result)) {
if ($prev != $row['type']) {
if ($prev) echo "</optgroup>";
echo "<optgroup label='{$row['type']}'>";
$prev = $row['type'];
}
echo "<option value='".$row['DetailID']."'>".$row['DetailName']."</option>"; }
echo "</optgroup>";