2012-07-02 22 views
-2

可能重複:
PHP get both array value and array keyPHP陣列 - 獲取鍵值

我使用Codeigniters' form_checkbox()方法。

使用foreach循環我創建了form_checkbox和窗體的標籤。這很好,但我需要從數組中獲取值。

我的陣列設置如下:

Array 
(
    [1] => Animals 
    [2] => Art and Culture 
    [3] => Children 
    [4] => Disability 
    [5] => Disaster Relief 
    [6] => Domestic Violence 
); 

我的PHP代碼如下:

<?php foreach($interests as $interest) 
     { 
      echo form_checkbox('user_interests[]', $interest); 
      echo "<label>$interest</label>"; 
     } 
?> 

這將產生HTML一樣:

<input type="checkbox" value="Animals" name="user_interests[]"> 

我希望它是數組中的值=「1」,「2」等。

我該如何得到這個?

回答

1

試試這個:

<?php foreach($interests as $k=> $interest) 
     { 
      $data= array('name'=>'user_interests[]', 'value'= $k) 
      echo form_checkbox($data); 
      echo "<label>$interest</label>"; 
     } 
?> 
5

更改你的循環是:

foreach($interests as $key => $interest) { 
    ... 
} 
2

使用此代碼:

foreach($interests as $key => $interest) 
1

像這樣:

foreach ($interests as $key => $interest) { 
    echo form_checkbox("user_interests[$key]", $interest); 
    echo "<label>$interest</label>"; 
} 
2

將您的php代碼更改爲:

foreach($interests as $key => $interest) 
{ 
    echo form_checkbox('user_interests[]', $key); 
    echo "<label>$interest</label>"; 
}