从循环中的复选框获取$ _POST

时间:2013-10-22 23:10:03

标签: php html arrays loops checkbox

我正在尝试在提交表单(类似验证)之后获取复选框的选中值,无论如何独立于选定的输入,我的代码无法决定用户选择了哪个输入。

例如: 选项1 选项2 备选方案3

如果用户选择了选项2,3,则代码选择选项1,2。 如果用户选择了选项2,则代码选择选项1。 仅当用户选择了选项1或选项1,选项2或每个选项时,代码才能正常工作。

for ($y=0;$y<$n; $y++) {
    $caption_and_value = explode(":",$before_explode[$y]); 
    $caption = caption_and_value[0];
    $value = caption_and_value[1];
    $match .= '<input type="checkbox" name="'.$name_form[$y].'" value="'.$value.'"'; 
    if (isset($_POST[$name_form][$y])) {
        $match .= ' checked="checked"';
    } else {
        $match .= ''; 
    } 
    $match.='>'.$caption.'<br />';  
}

请告诉我,如果我做错了什么,我几个小时都想不出来。 谢谢!

2 个答案:

答案 0 :(得分:3)

您应该使用一系列复选框,更容易处理:

<input type="checkbox" name="boxes[]">
<input type="checkbox" name="boxes[]">
<input type="checkbox" name="boxes[]">

...然后在PHP中:

foreach($_POST['boxes'] as $key => $value) {
    echo $key . ': ' . $value;
}

答案 1 :(得分:0)

我有这个。这是表格:

<form method='POST' action = 'process.php'>
<?php 
for ($i=1;$i<=3;$i++){
echo "<input type='checkbox' name='box[]' value='$i'>$i<br>";
}
?>
<input type='submit' value='send'>
</form>

这是php:

    <?php 
    $input_value = $_POST['box'];
    $i = 0;
    $choice1 = NULL;
    $choice2 = NULL;
    $choice3 = NULL;
    foreach ($input_value as $value){
    if ($value == "1"){
    $choice1 = "active";
    }
    if ($value == "2"){
    $choice2 = "active";
    }
    if ($value == "3"){
    $choice3 = "active";
    }
    }
//choice checker script block
    if (!isset($choice1) and !isset($choice2) and !isset($choice3)){
    echo "You didn't choose anything!";
    }
    if ($choice1 == "active" and $choice2 == NULL and $choice3 == NULL){
    echo "You only chose 1";
    }
    if ($choice2 == "active" and $choice1 == NULL and $choice3 == NULL){
    echo "You only chose 2";
    }
    if ($choice3 == "active" and $choice2 == NULL and $choice1 == NULL){
    echo "You only chose 3";
    }
    if ($choice1 == "active" and $choice2 == "active" and $choice3 == NULL){
    echo "You chose 1 and 2";
    }
    if ($choice1 == "active" and $choice3 == "active" and $choice2 == NULL){
    echo "You chose 1 and 3";
    }
    if ($choice3 == "active" and $choice2 == "active" and $choice1 == NULL){
    echo "You chose 2 and 3";
    }
    if ($choice1 == "active" and $choice2 == "active" and $choice3 == "active"){
    echo "You chose all of the choice!";
    }
// end of choice checker script blok
    ?>

可能有点杂乱和大量的代码。 :D
但是,如果你想检查用户选择的选项,我已经在上面创建了“选择检查器脚本” 实际上,您可以使用if($choice == 'active')更改或替换if(isset($choice)),但它会返回相同的内容。 试试吧!你会知道如何定制它。
我认为这就是你要找的东西。