[英]Radio buttons in foreach loop
我從數據庫中提取了一系列問題,需要為每個問題循環單選按鈕。 我需要將所有答案返回到一個看起來像這樣的數組
$answer_grp1 = array("T", "T", "T");
我的代碼看起來像這樣。 將數組放入$ _POST ['answer_grp1']的正確(name = ??)語法是什么
<?php foreach ($questions as $question):
if ($question['q_type']==1): ?>
<tr>
<td style="width:5%;"><?= $question['q_number'] ?></td>
<td style="width:15%;">
T<input type="radio" name=answer_grp1[] value="T" />
F<input type="radio" name=answer_grp1[] value="F" />
</td>
<td><?= $question['q_text'] ?></td>
</tr>
<?php endif;
endforeach; ?>
我傾向於使用for循環代替:
<?php
for ($i = 0; $i < count($questions); $i++) {
$question = $questions[$i];
if ($question['q_type']==1): ?>
<tr>
<td style="width:5%;"><?= $question['q_number']; ?></td>
<td style="width:15%;">
T<input type="radio" name=answer_grp1[<?php print $i; ?>] value="T" />
F<input type="radio" name=answer_grp1[<?php print $i; ?>] value="F" />
</td>
<td><?= $question['q_text']; ?></td>
</tr>
<?php endif;
endfor; ?>
這是你的代碼:
<?php
$i = 0;
foreach ($questions as $question):
if ($question['q_type']==1): ?>
<tr>
<td style="width:5%;"><?= $question['q_number']; ?></td>
<td style="width:15%;">
T<input type="radio" name=answer_grp1[<?php print $i; ?>] value="T" />
F<input type="radio" name=answer_grp1[<?php print $i; ?>] value="F" />
</td>
<td><?= $question['q_text']; ?></td>
</tr>
<?php endif; ?>
<?php
$i++
endforeach; ?>
你會用的
$_POST['answer_grp1'][0]
$_POST['answer_grp1'][1]
... 等等。
如果所有答案都在這個數組中,你也可以像這樣循環:
for ($x=0; $x<count($_POST['answer_grp1']); $x++)
{
$value = $_POST['answer_grp1'][$x];
}
只要所有字段都在一個<form>
標記內並且您提交表單,那么該數組應該在$_POST
全局中可用。
您對每個輸入的命名, answer_grp1[]
是正確的; 但是你應該在名稱周圍添加引號。
您還應該在問題輸出后添加分號 - 更改此:
<?= $question['q_text'] ?>
對此:
<?= $question['q_text']; ?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.