我有一个user_groups
表
id parent_id title
1 0 Public
2 1 Registered
3 2 Author
4 3 Editor
12 2 Customer Group (Example)
您可以在这里看到Register(2)有2个子id(3,12),id(3)也有它的子id(4)。所以这就是创造一棵树。现在我需要在列表框中制作这样的树。所以我试过这样做:
<?php
$db = JFactory::getDbo();
$query = "select grp.id, grp.title from #__usergroups AS grp where parent_id=2";
$db->setQuery($query);
$groups = $db->loadObjectList();
?>
<tr>
<td>Select Group</td>
<td>
<select name="usergroup">
<option value="0"><?='Select Group';?></option>
<?
foreach($groups as $group) {
$query = "select grp.id, grp.title from #__usergroups AS grp where parent_id=".$group->id;
$db->setQuery($query);
$groups2 = $db->loadObjectList();
?>
<option value="<?=$group->id?>"><?=$group->title?></option>
<? if($groups2!=''){
foreach($groups2 as $group2){
$query = "select grp.id, grp.title from #__usergroups AS grp where parent_id=".$group2->id;
$db->setQuery($query);
$groups3 = $db->loadObjectList();
?>
<option value="<?=$group2->id?>">--<?=$group2->title?></option>
<?
if($groups3!=''){
foreach($groups3 as $group3){
$query = "select grp.id, grp.title from #__usergroups AS grp where parent_id=".$group3->id;
$db->setQuery($query);
$groups4 = $db->loadObjectList();
?>
<option value="<?=$group3->id?>">----<?=$group3->title?></option>
<?
if($groups4!=''){
foreach($groups4 as $group4){
?>
<option value="<?=$group4->id?>">--------<?=$group4->title?></option>
<?
}
}
}
}
}
}
}?>
</select>
</td>
</tr>
但这不是最好的方法。如果我添加更多的子项目,那么在我达到另一个级别之前,这将不起作用。所以我需要有效的方法来做到这一点,这样我就不需要在未来增加水平。请帮忙!
您可以使用optgroup
进行类似的操作
<select>
<optgroup label="Group 1">
<option>Option 1.1</option>
</optgroup>
<optgroup label="Group 2">
<option>Option 2.1</option>
<option>Option 2.2</option>
</optgroup>
<optgroup label="Group 3" disabled>
<option>Option 3.1</option>
<option>Option 3.2</option>
<option>Option 3.3</option>
</optgroup>
</select>
阅读此https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup