比较foreach和复选框的值

时间:2015-09-29 09:27:40

标签: php mysql foreach

我有一个foreach循环,它会将格式为“1,2”的文本拆分为“1 2”。

我试图将每个分割值与$ rowCentral ['tuitionAreaID']进行比较,当匹配时,将选中复选框。我能够实现这一点,但是,我的所有复选框都是重复的。

    <?php
while($rowCentral=mysql_fetch_array($resultCentral))
    {
    ?>
    <?php
    foreach($myArray as $my_Array){
    //echo $my_Array.'<br>';  
    ?>
    <input type="checkbox" name="centralArea[]" value="<?php echo $rowCentral['tuitionAreaID']?>" <?php if($my_Array == $rowCentral['tuitionAreaID']){echo "checked";}?>> <?php echo $rowCentral['tuitionAreaDesc']?><br>
    <?php
    }
    ?>
    <?php       
    }
    ?>

这是上面显示的代码的输出(每行重复):

 Anson, Tanjong Pagar
 Anson, Tanjong Pagar
 Beach Road, High St, Hill St
 Beach Road, High St, Hill St
 Cairnhill, Newton, Orchard, Scotts Rd
 Cairnhill, Newton, Orchard, Scotts Rd
 Cecil, Chinatown, Marina, People's Park, Raffles Place
 Cecil, Chinatown, Marina, People's Park, Raffles Place

1 个答案:

答案 0 :(得分:1)

我认为你想要实现的是......你应该检查你是否需要单独设置复选框的checked属性,并在你的foreach中测试它,然后只回显一次复选框....请注意,我没有测试过我的代码..

<?php
while($rowCentral=mysql_fetch_array($resultCentral))
{       
    $checked = "";
    foreach($myArray as $my_Array)
    {
       if($my_Array == $rowCentral['tuitionAreaID'])
       {
         $checked = "checked";
       }           
    }
    echo "<input type='checkbox' name='centralArea[]' value='".$rowCentral['tuitionAreaID']."' ".$checked.">".$rowCentral['tuitionAreaDesc']."<br>"
}