Selectbox父缩进

时间:2013-10-07 10:23:32

标签: php mysql categories drop-down-menu indentation

我有一个simlpe选择框。它打印出来很好,但我希望它缩进子类 所以布局看起来像:

Hardware
 - CPU
 - Motherboards
  -- MSI
  -- ASUS
Screens
 - Dell
  -- 27"
Acer

在我的数据库中,表定义为:

ID - Label - Parent

我目前的代码是:

<select label="users" id="cat" onchange="showUser(this.value)" style="width:100%;padding:3px;cursor:pointer;">
<option value="">-- Choose category -- </option>
<?php 
$categories = $mysqli->query("SELECT * FROM medialib_cats");
while($row = $categories->fetch_assoc()){?>
    <option value="<?php echo $row['id']; ?>">
    <?php echo $row['label']; ?>
    </option>

<?php } ?>
</select>

我尝试将结果分组,但它不起作用。如何使用php / mysqli自动缩进?我猜我应该使用递归? 我想只是缩进行 - 而不是使用optgroup请:)

3 个答案:

答案 0 :(得分:1)

选项可以使用optgroups:

<select label="users" id="cat" onchange="showUser(this.value)" style="width:100%;padding:3px;cursor:pointer;">
<option value="">-- Choose category -- </option>
<?php 
$categories = $mysqli->query("SELECT * FROM medialib_cats");
while($row = $categories->fetch_assoc()){
    if ($lastgrp != $row['parent']) {
        if ($lastgrp!="") echo "</optgroup>";
        $lastgrp = $row['parent'];
        echo "<optgroup>".$lastgrp;
    }
    echo "<option value="+ $row['id'] + ">"+  $row['label'] + "</option>";

} ?></optgroup>
</select>

答案 1 :(得分:1)

使用<optgroup>是将选择选项组合在一起的标准方法。

$options    = array();
$categories = $mysqli->query("
  SELECT 
    id, label, p.label as parent_label 
  FROM 
    medialib_cats AS child
  INNER JOIN
    medialib_cats AS p ON p.id = child.parent
");
foreach($categories as $category) {
  $parent = $category['parent_label'];
  if (! isset($options[$parent])) $options[$parent] = array();
  $options[$parent][$category['id']] = $category['label'];
}
echo "<select>";
foreach($options as $group => $option) {
  printf('<optgroup label="%s">', $group);
  foreach ($option as $id => $label) {
    printf('<option value="%s">%s</option>', $id, $label);
  }
  printf('</optgroup>');
}
echo "</select>";

我已经创建了一个CodePad example(将db结果模拟为数组)并使其正常工作。

答案 2 :(得分:0)

嗯......猜猜我会尝试不使用optgroup。似乎它导致了一些问题。 还可以在optgroup中找到您无法在选择框中选择父0的情况? 如何通过php在selectbox中添加缩进?

相关问题