php如何在选择下拉列表中显示类别和子类别?
我有一个保存类别和产品名称的表: +-----------------------+ | products | +-----------------------+ | id name cat_name | | 1 lily flower | | 2 hibiscus flower | | 3 cat animal | | 4 dog animal | +-----------------------+php如何在选择下拉列表中显示类别和子类别?,php,html,mysql,Php,Html,Mysql,我有一个保存类别和产品名称的表: +-----------------------+ | products | +-----------------------+ | id name cat_name | | 1 lily flower | | 2 hibiscus flower | | 3 cat animal | | 4 dog animal | +-----------------------+
如何在选择列表中实现这一点。请提供帮助。在html正文中,是optgroup标记对选项进行分组
<select>
<optgroup label="flower">
<option value="whatever">lily</option>
<option value="whatever">hibiscus</option>
</optgroup>
...
</select>
百合花
木槿
...
希望你能明白。
注意,这些optgroup看起来很差。也许你还需要一些jquery插件来获得你想要的东西。在html正文中,是optgroup标记对选项进行分组
<select>
<optgroup label="flower">
<option value="whatever">lily</option>
<option value="whatever">hibiscus</option>
</optgroup>
...
</select>
百合花
木槿
...
希望你能明白。
注意,这些optgroup看起来很差。也许你还需要一些jquery插件才能得到你想要的。如果你能得到这样的数组
array(
array(
'id' => 1
'name' => 'lily',
'cat_name' =>'flower'
),
array(
'id' => 2
'name' => 'hibiscus',
'cat_name' =>'flower'
),
.....
);
然后通过cat对数据进行分组
$groups = array();
foreach ($results as $rs) {
$key = $rs['cat_name'];
if (!isset($groups[$key])){
$groups[$key] = array();
}
$groups[$key][] = $rs;
}
然后循环$groups,回显html选项,如
//this not php code
loop groups {
echo optgroup opentag
loop groups[cat_name]{
echo option tag
}
echo optgroup close tag
}
如果你能得到这样的数组
array(
array(
'id' => 1
'name' => 'lily',
'cat_name' =>'flower'
),
array(
'id' => 2
'name' => 'hibiscus',
'cat_name' =>'flower'
),
.....
);
然后通过cat对数据进行分组
$groups = array();
foreach ($results as $rs) {
$key = $rs['cat_name'];
if (!isset($groups[$key])){
$groups[$key] = array();
}
$groups[$key][] = $rs;
}
然后循环$groups,回显html选项,如
//this not php code
loop groups {
echo optgroup opentag
loop groups[cat_name]{
echo option tag
}
echo optgroup close tag
}
使用
select
sql语句,然后将结果循环到新的分类数组(在其中抛出一些html以便更好地度量),然后对数组进行内爆。这就是我要做的…^使用orderby
并按cat\u name
排序,这样你所有的动物、花等都在一起了。@chris85我试过按顺序排序,但我没有得到确切的结果。你能解释一下吗?我如何在for循环中迭代它?我在这里得到了一个有效的答案:)使用select
sql语句,然后将结果循环到新的分类数组(为了更好的度量,在其中加入一些html),然后对数组进行内爆。这就是我要做的…^使用order by
并按cat\u name
排序,这样你所有的动物、花等都在一起了。@chris85我试过按顺序排序,但我没有得到确切的结果。你能解释一下吗?我如何在for循环中迭代它?我在这里得到了一个有效的答案:)