我在index.php中有一个select表单对象。这些项目来自mySQL。我想要实现的是:每当catID = NULL时创建一个optgroup。在这种情况下,Section1和Section2应该是optgroups。但是,选择组在1个选项后关闭。有小费吗?截图:
数据库 - >表:
catId catName
NULL --Section1--
1010 Bilar
1020 Bildelar & tillbehör
1030 Motorcycklar
1040 Motorcycklar delar & tillbehör
1050 Moped
1070 Lastbil & Truck
NULL --Section2--
2010 Bygg och Trädgår
2020 Möbler & Heminredning
2030 Husgeråd & Vitvaror
2040 Verktyg
HTML:
<?php $count = 0; ?>
<?php foreach($categories as $category ): $count++;?>
<?php if($category['catId']==NULL){?>
<optgroup label="<?php $category['catName']?>">
<?php } else{ ?>
<option value="<?php echo $category['catId'];?>"><?php echo $category['catName'];?></option>
<?php
$temp = $categories[($count+1)];
if($temp['catId']==NULL)?>
</optgroup>
<?php } ?>
<?php endforeach;?>
</select>
答案 0 :(得分:1)
试试这个:
<?php $first_opt = TRUE; ?>
<?php foreach($categories as $category ): ?>
<?php if($category['catId']==NULL){?>
<?php if($first_opt):?>
<optgroup label="<?php echo $category['catName']?>">
<?php $first_opt = FALSE;?>
<?else:?>
</optgroup><optgroup label="<?php echo $category['catName']?>">
<?endif;?>
<?php } else{ ?>
<option value="<?php echo $category['catId'];?>"><?php echo $category['catName'];?></option>
<?php } ?>
<?php endforeach;?>
</optgroup>
</select>