嵌套下拉菜单
时间:2020-03-06 14:56:55 来源:igfitidea点击:
我正在用php / mysql构建表单。我有一张带有位置和子位置列表的表。每个子位置都有一个父位置。列" parentid"引用同一表中的另一个locationid。我现在想通过以下方式将这些值加载到下拉列表中:
--Location 1 ----Sublocation 1 ----Sublocation 2 ----Sublocation 3 --Location 2 ----Sublocation 4 ----Sublocation 5
等等等
有人为此提供了一个优雅的解决方案吗?
解决方案
我们是否正在寻找OPTGROUP标签之类的东西?
optgroup绝对是必经之路。实际上就是它的目的
例如,在" Grandhall Grill Used"下查看选择器的源代码http://www.grandhall.eu/tips/submit/。
我们可以在实际的HTML中使用空格和破折号缩进。不过,我们将需要一个recusrive循环来构建它。就像是:
<?php
$data = array(
'Location 1' => array(
'Sublocation1',
'Sublocation2',
'Sublocation3' => array(
'SubSublocation1',
),
'Location2'
);
$output = '<select name="location">' . PHP_EOL;
function build_items($input, $output)
{
if(is_array($input))
{
$output .= '<optgroup>' . $key . '</optgroup>' . PHP_EOL;
foreach($input as $key => $value)
{
$output = build_items($value, $output);
}
}
else
{
$output .= '<option>' . $value . '</option>' . PHP_EOL;
}
return $output;
}
$output = build_items($data, $output);
$output .= '</select>' . PHP_EOL;
?>
或者类似的东西;)
注意:这只是伪代码。尽管我们应该能够根据需要调整概念,但我没有尝试运行它。
$parentsql = "SELECT parentid, parentname FROM table";
$result = mysql_query($parentsql);
print "<select>";
while($row = mysql_fetch_assoc($result)){
$childsql = "SELECT childID, childName from table where parentid=".$row["parentID"];
$result2 = mysql_query($childsql);
print "<optgroup label=\".$row["parentname"]."\">";
while($row2 = mysql_fetch_assoc($result)){
print "<option value=\"".$row["childID"]."\">".$row["childName"]."</option>\n";
}
print "</optgroup>";
}
print "</select>";
牢记BaileyP的正确批评,这是在没有在每个循环中调用多个查询的开销的情况下执行以下操作的方法:
$sql = "SELECT childId, childName, parentId, parentName FROM child LEFT JOIN parent ON child.parentId = parent.parentId ORDER BY parentID, childName";
$result = mysql_query($sql);
$currentParent = "";
print "<select>";
while($row = mysql_fetch_assoc($result)){
if($currentParent != $row["parentID"]){
if($currentParent != ""){
print "</optgroup>";
}
print "<optgroup label=\".$row["parentName"]."\">";
$currentParent = $row["parentName"];
}
print "<option value=\"".$row["childID"]."\">".$row["childName"]."</option>\n";
}
print "</optgroup>"
print "</select>";
理想情况下,我们将按正确的顺序从数据库中选择所有这些数据,然后将其循环以进行输出。这是我对你要的东西的看法
<?php
/*
Assuming data that looks like this
locations
+----+-----------+-------+
| id | parent_id | descr |
+----+-----------+-------+
| 1 | null | Foo |
| 2 | null | Bar |
| 3 | 1 | Doe |
| 4 | 2 | Rae |
| 5 | 1 | Mi |
| 6 | 2 | Fa |
+----+-----------+-------+
*/
$result = mysql_query( "SELECT id, parent_id, descr FROM locations order by coalesce(id, parent_id), descr" );
echo "<select>";
while ( $row = mysql_fetch_object( $result ) )
{
$optionName = htmlspecialchars( ( is_null( $row->parent_id ) ) ? "--{$row->descr}" : "----{$row->desc}r", ENT_COMPAT, 'UTF-8' );
echo "<option value=\"{$row->id}\">$optionName</option>";
}
echo "</select>";
如果我们不喜欢使用coalesce()函数,则可以在此表中添加一个" display_order"列,然后手动设置该列,然后将其用于" ORDER BY`"。

