循环中具有不同标签的多个复选框

时间:2012-01-12 13:14:53

标签: php

<?php
    $r=mysql_query("SELECT city.id as city_id, locality.id,locality.area_name  ".
                   "FROM city, locality  ".
                   "WHERE city.id = locality .city_id order by city_id"); 

    while($rss=mysql_fetch_object($r))
    {
?>
<legend><?=$rss->city_id?></legend>
<input type="checkbox" name="sub_type[]" id="sub_type" value="<?=$rss->id?>" />
<span><?=$rss->area_name?></span><br/>
<?php
    }
?>

我正在显示区域名称,并将其城市ID作为标签。问题是由于周围的while循环,为每个区域名称添加了此ID标签。如何防止ID标签重复多次,以便将复选框分组到它们所属的城市ID下?

2 个答案:

答案 0 :(得分:1)

<legend>移动到外面 while循环。

(使用<label>而不是<span> ...您还需要修复输入的id,它们必须唯一

答案 1 :(得分:1)

怎么样:

<?php
$r=mysql_query("SELECT city.id as city_id, locality.id,locality.area_name  ".
               "FROM city, locality  ".
               "WHERE city.id = locality .city_id order by city_id"); 
$previous = '';
while($rss=mysql_fetch_object($r)) { ?>
    <?php if (empty($previous) || $previous != $rss->city_id) { ?>
        <legend><?=$rss->city_id?></legend>
    <?php } ?> 
    <?php $previous = $rss->city_id; ?>
    <input type="checkbox" name="sub_type[]" id="sub_type" value="<?=$rss->id?>" />
    <span><?=$rss->area_name?></span><br/>
<?php
}
?>