1

我有一个用 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 方法检索数组中的内容以进行表单验证。

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

4

3 回答 3

1

对于变量:

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

对于数组:

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

希望这能解决这个谜团;)

于 2012-05-25T16:15:07.330 回答
1

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

<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>
于 2012-05-25T16:16:47.347 回答
0

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

<?
$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>

It produces HTML output as follows:

<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>

And $_POST looks like this:

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

However, doing this exposes your info to outsiders, which is generally bad, since it can expose you to web attacks. I'd recommend to store this array in $_SESSION and use simple check on those checkboxes; if that's not possible, consider using serialize() and some encryption, and then decrypting + unserialize() after you've received $_POST. It requires more work, but is much safer.

于 2012-05-25T17:30:51.220 回答