-1

我有一个简单的选择框。它打印得很好,但我希望它缩进 subcats 所以布局看起来像:

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>

我尝试使用 group by 对结果进行分组,但它没有用。如何使用 php/mysqli 自动缩进?我想我应该使用递归?我只想用 -- 缩进这些行,请不要使用 optgroup :)

4

3 回答 3

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>
于 2013-10-07T10:31:09.187 回答
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 示例(将 db 结果模拟为数组)并使其正常工作。

于 2013-10-07T10:33:13.927 回答
0

嗯...我想我会尽量不使用 optgroup。似乎它引起了一些问题。还发现 optgroup 不能在选择框中选择父 0?通过php在选择框中添加缩进--怎么样?

于 2013-10-07T11:06:18.067 回答