传递一个HTML复选框数组(带空值)给PHP


Passing an HTML Checkbox Array (w/ Empty Values) to PHP

我有问题传递HTML复选框数组PHP与类似的代码:

$cbArray = checkbox($_POST['cbArray']);
$cbArray = array_chunk($cbArray, 4);
$id = $_POST['id'];
$idcount = count($id);
$id = array_chunk($id, 4);
$cbOuterArrays = 0;
if( $idcount > 16 ){
        $cbOuterArrays = 4;
    }elseif( $idcount > 12 ){
        $cbOuterArrays = 3;
    }elseif( ($idcount > 8 ){
        $cbOuterArrays = 2;
    }elseif( $idcount > 4 ){ 
        $cbOuterArrays = 1;
    }
for( $i = 0; $i <= $cbOuterArrays; $i++ ){
    $c = 0;
    if(isset($id[$i][$c])){
        if($cb[$i][$tc] == 'x'){
            echo "1st checked in chunk " . $c;
        }
    }
    $c++
    if(isset($id[$i][$c])){
        if($cb[$i][$tc] == 'x'){
            echo "2st checked in chunk ". $c;
        }
    }
    $c++
    if(isset($id[$i][$c])){
        if($cb[$i][$tc] == 'x'){
            echo "3st checked in chunk . $c;
        }
    }
    $c++
    if(isset($id[$i][$c])){
        if($cb[$i][$tc] == 'x'){
            echo "4st checked in chunk . $c;
        }
    }
}
?>

我的HTML是类似这样的:

<html>
    <input type="text" name="id[]">
    <input type="checkbox" name="cb[]"> //I have tried value="1" as well but it didn't help
    //Then I have a button that runs js to add more checkboxes
    <input type="submit" value="Submit">
</html>

无论我选中哪个复选框,如果我只选中一个,它会返回"第一次在块0中选中"。就好像它只拉入填充值。如果代码看起来很糟糕,请原谅。我试图删除所有无关的东西,而留下任何可能是问题的原因。我认为我的复选框函数将检查每个值,如果它是空的,使其在数组中的空白。我如何让它识别空复选框?

编辑:

正如MaggsWeb所说,我不能发送空复选框。我将复选框功能更改为:

<?php
function cb($x){
    $a = [];                     #Create new array
    $cv = 0;                     #Current new array value
    foreach($_POST[$x] as &$v){  #Loop through the first array
        while($cv < intval($v)){ #If the new array is not at the old arrays value loop
            $a[$cv] = ' ';       #Fill the new array value with blank space
            $cv++;               #Move to next value in new array
        }                        #Repeat if not at the value yet
        $a[$cv] = 'x';           #Set the current value of new array to 'x'
        $cv++;                   #Move to next value in new array
    }                            #Move to next value in old array & Repeat
    return $a;                   #Return the new array
}
#and call it via cb('id');
?>

复选框值只有在被选中时才会被发送。

复选框的名称不一定是"数组"格式,除非有很多。在这种情况下,每个都需要一个不同的值。

不确定所有的代码在做什么。您似乎没有在任何地方检查if ( is_array ( $_POST['cb'] ) ) { ...

您可以使用hidden元素来获取未检查的值。试试这样做:

<input type="hidden" name="checkbox" value="unchecked" />
<input type="checkbox" name="checkbox" id="checkbox1" value="checked" />

当您的复选框未选中时,则$_POST['checkbox']值来自隐藏元素。