[英]How to put categories and subcategories on selectbox with optgroup with just one query with PHP?
I would like to know how is possible with one just query make the selectbox with categories and subcategories with optgroup.我想知道如何仅通过一个查询就可以使用 optgroup 生成带有类别和子类别的选择框。
Table category:表类别:
cat_id int(10) unsigned Auto Increment
cat_catid int(10) unsigned NULL
cat_name varchar(100)
Content:内容:
| cat_id | cat_catid | cat_name |
+--------+-----------+----------------
| 1 | NULL | Category - A |
| 2 | 1 | 1 |
| 3 | 1 | 2 |
| 4 | NULL | Category - B |
| 5 | 4 | 1 |
| 6 | 4 | 2 |
| 7 | 4 | 3 |
With one query and PHP make it into:通过一个查询,PHP 将其变为:
<select>
<optgroup label="Area - A">
<option>1</option>
<option>2</option>
</optgroup>
<optgroup label="Area - B">
<option>1</option>
<option>2</option>
<option>3</option>
</optgroup>
</select>
You're going to need some post processing in PHP of your query.您将需要在 PHP 中对查询进行一些后期处理。 I prefer restructuring the rows to a multidimensional array:
我更喜欢将行重组为多维数组:
$rows = query("SELECT * FROM table ORDER BY cat_catid"); // (Just make sure NULL's are first)
$cats = [];
foreach ( $row as $row ) {
// Do we have a root category?
if ( $row['cat_catid'] === null ) {
// Start a new array, and no children
$cats[ $row['cat_id'] ] = [
'name' => $row['cat_name'],
'children' => []
];
} else {
// Add this category name to the parent category ID.
$cats[ $row['cat_catid'] ]['children'][] = $row['cat_name'];
}
}
echo '<select>';
foreach ( $cats as $cat ) {
echo '<optgroup label="', $cat['name'], '">';
foreach ( $cat['children'] as $child ) {
echo '<option>', $child, '</option>';
}
echo '</optgroup>';
}
echo '</select>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.