表单:复选框,名称属性 - 传递数组


Forms: Checkboxes , name attribute - passing an array

>我有一个用HTML编码的复选框,到目前为止一切正常,但是我需要在复选框的name属性中传入一个数组。我知道当您将变量传递到 name 属性中时,这很容易做到。但对于数组来说,它被证明是更棘手的。

这是我的代码:

   <?php // spit out rest of the list
       $permiCheck = array();
       foreach($pList as $value){
        //go into array, get what is needed to pass into the name attribute
        echo '<tr>';
        echo '<td>';
        echo $value['PName'];
        echo '</td>';
        //pass an array in
        $permiCheck['Id'] = $value['Id'];
        $permiCheck['ItemId'] = $value['ItemId'];
        if($value['Id']!=null) {

        ?>
        <td style="text-align:center;"> <input type="checkbox" checked="yes" name="<?php $permiCheck;?>" value="" id="change"></td>

完成此操作后,我打算通过 POST 方法检索数组中的内容以进行表单验证。

知道我该怎么做,非常感谢。

复选框元素的名称必须是字符串,但是您可以将复选框用作数组。即

<input type="checkbox" name="checkboxName[]" value="1"/>
<input type="checkbox" name="checkboxName[]" value="2"/>

会回来

var_dump($_POST)
array
  'checkboxName' => 
    array
      0 => int 1
      1 => int 2

我不确定你想做什么,但也许你可以这样做

<td style="text-align:center;">
    <input type="checkbox" checked="yes" name="<?=$permiCheck['ItemId']?>[]" value="<?=$permiCheck['Id']?>" id="change">
</td>

对于变量:

<input type="checkbox" name="myVariable" />

对于数组:

<input type="checkbox" name="myArray[]" />
<input type="checkbox" name="myArray[]" />
<input type="checkbox" name="myArray[]" />

希望这能解决迷雾;)

实际上,您可以将数组作为值传递,这些数组甚至可以是多维的:

<?
$testarray = array('id'=> 1, 'value'=>"fifteen");
var_dump($_POST);
?>
<form method="post">
<input type="checkbox" checked="yes" name="permicheck[id1]" value="<?php print_r($testarray)?>" id="change">
<input type="checkbox" checked="yes" name="permicheck[id2]" value="<?php print_r($testarray)?>" id="change">
<input type="submit">
</form>

它生成如下 HTML 输出:

<form method="post">
<input type="checkbox" checked="yes" name="permicheck[id1]" value="Array
(
    [id] => 1
    [value] => fifteen
)
" id="change">
<input type="checkbox" checked="yes" name="permicheck[id2]" value="Array
(
    [id] => 1
    [value] => fifteen
)
" id="change">
<input type="submit">
</form>

$_POST 看起来像这样:

Array ( 
    [permicheck] => 
        Array ( 
        [id1] =>
            Array ( [id] => 1 [value] => fifteen ) 
        [id2] => 
            Array ( [id] => 1 [value] => fifteen ) 
        )
     )

但是,这样做会将您的信息暴露给外部人员,这通常是不好的,因为它会使您遭受网络攻击。我建议将此数组存储在 $_SESSION 中,并对这些复选框进行简单的检查;如果这是不可能的,请考虑使用 serialize() 和一些加密,然后在收到 $_POST 后解密 + unserialize()。它需要更多的工作,但更安全。