2012-05-25 34 views
1

我有一個複選框以HTML編碼,到目前爲止一切正常,但我需要在複選框的名稱屬性中傳遞數組。當你將一個變量傳遞給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方法在數組中。

任何想法我可以做到這一點,非常感謝。

+0

給出一個以[]結尾的名稱。當PHP收到它時,它會自動將其解釋爲一個數組。 – j08691

+0

我將PHP數組($ permiCheck)(這是一個2d數組)傳入名稱屬性中。這仍然適用? – thejoker

+0

它不適用,因爲您無法將數組傳遞給屬性。請閱讀下面的評論 –

回答

1

複選框元素的名稱必須是一個字符串,則但可以使用複選框作爲數組。 即

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

是的,你是對的,似乎有兩個混合起來。我想我有興趣將數組傳遞給value字段,以便通過post方法 – thejoker

+0

進行後續檢索,您可能想要使用value =「<?= $ permiCheck ['ItemId']​​?> _ <?= $ permiCheck [''在這種情況下,在你的複選框元素中,然後當你獲取$ _POST –

+0

時爆炸它是的,我看到你在做什麼,你用爆炸來使用'_'作爲指導來分離它?所以value屬性不能傳遞數組,所有你能做的就是連接這樣的字符串? – thejoker

1

對於一個變量:

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

對於數組:

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

希望這解決了謎)

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> 

它產生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()。它需要更多的工作,但更安全。

相關問題