我有一个表单用于多个复选框条目。
我可以使用 foreach 函数循环获取数据。
foreach($_POST['competition'] as $value) {
echo "Value = $value <br>";
}
<input type="checkbox" name="competition[]" value="comp 1">
<input type="checkbox" name="competition[]" value="comp 2">
<input type="checkbox" name="competition[]" value="comp 3">
这完全返回了我所需要的内容,但是某些竞赛将有一个用于答案的输入字段。
<label for="text">Answer <strong>A, B or C </strong></label>
<input type="text" name="answer1" value="" />
<input type="checkbox" name="competition[]" value="comp 1">
<input type="checkbox" name="competition[]" value="comp 2">
<label for="text">Answer <strong>A, B or C </strong></label>
<input type="text" name="answer2" value="" />
<input type="checkbox" name="competition[]" value="comp 3">
如果有人勾选了输入并且还写了答案,我将如何循环并确保正确的答案将返回到“foreach”(假设他们已在输入字段中输入了一些内容)
我想看看
Value = comp1 - Answer = $answer1
Value = comp2
Value = comp3 - Answer = $answer3
如果在输入字段中输入了某些内容,则当我使用 foreach $_POST['comp']
循环时返回它
最佳答案
您可能需要分解并重命名此处的一些字段:
<label for="text">Answer <strong>A, B or C </strong></label>
<input type="text" name="answer1" value="" />
<input type="checkbox" name="answer_1_competition[]" value="comp 1">
<input type="checkbox" name="answer_1_competition[]" value="comp 2">
<label for="text">Answer <strong>A, B or C </strong></label>
<input type="text" name="answer2" value="" />
<input type="checkbox" name="answer_2_competition[]" value="comp 1">
<?php
$answer_keys = array(1, 2);
$answers = array();
foreach($answer_keys as $index)
{
$answers[$index] = array(
'answer' => '',
'competition' => array(),
);
if(isset($_POST['answer' . $index]))
$answers[$index]['answer'] = $_POST['answer' . $index];
if(isset($_POST['answer_' . $index . '_competition']))
foreach($_POST['answer_' . $index . '_competition'] as $comp)
$answers[$index]['competition'][] = $comp;
}
print_r($answers);
/*
* Should look something like
*
* Array(
* 1 => array(
* 'answer' => 'Something',
* 'competition' => array(
* 'comp1',
* )
* ),
* etc
* )
*
*/
这就是我所拥有的,但我不喜欢它。但是,我不确定解决这个问题的最佳方法。有关文本和复选框如何相互关联的更多详细信息可能会有所帮助。
关于php - PHP foreach后返回不同的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24123616/