我有一个输入表单,允许我将新测验插入数据库。表单看起来像这样:
Question Title
Question #1
is_correct_1
choice#1
is_correct_2
choice#2
is_correct_3
choice#3
is_correct_4
choice#4
Question #2
.
.
.
不同的测验会有不同数量的问题(尽管每个问题总是有 4 种可能性)。我确定在构建表格之前它会有多少问题。为了实现这一点,我使用几个 for 循环生成了表单。我还以相同的方式初始化不同输入字段的名称。见下文:
// Grab number of questions from Admin page
$num_of_Qs = $_POST['num_of_Qs'];
// Produce form by using for loops
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
echo '<fieldset><legend>New Quiz Details</legend><label for="title">Quiz Title</label>';
echo '<input type="text" id="title" name="title" value="" /><br /><br />';
for ($i = 1; $i <= $num_of_Qs; $i++) {
echo '<label for="question_'.$i.'">Question #'.$i.'</label>';
echo '<input type="text" id="question_'.$i.'" name="question_'.$i.'" value="" /><br /><br />';
for ($x = 1; $x <= 4; $x++) {
echo '<label for="is_correct_'.$i.'_'.$x.'">is_correct_'.$x.'</label>';
echo '<input type="text" id="is_correct_'.$i.'_'.$x.'" name="is_correct_'.$i.'_'.$x.'" value="" /><br />';
echo '<label for="choice_'.$i.'_'.$x.'">Choice #'.$x.'</label>';
echo '<input type="text" id="choice_'.$i.'_'.$x.'" name="choice_'.$i.'_'.$x.'" value="" /><br /><br />';
}
}
echo '</fieldset><input type="hidden" name="num_of_Qs" value="'.$num_of_Qs.'" />';
echo '<input type="submit" value="Create" name="create" /></form>';
因此,变量最终看起来像这样:
$title
$question_1
is_correct_1_1
choice_1_1 // first question, first choice
is_correct_1_2
choice_1_2 // first question, second choice
...
当我通过使用 $_POST 函数获取变量来存储这些变量时,我遇到了麻烦。这是我的代码:
// If user has submitted New Quiz data
if (isset($_POST['create'])) {
$num_of_Qs = $_POST['num_of_Qs'];
$title = $_POST['title'];
for ($i = 1; $i <= $num_of_Qs; $i++) {
$question_$i = $_POST['question_'.$i.''];
for ($x = 1; $x <= 4; $x++) {
$is_correct_$i_$x = $_POST['is_correct_'.$i.'_'.$x''];
$choice_$i_$x = $_POST['choice_'.$i.'_'.$x.''];
}
}
print_r($title);
print_r($question_1);
exit();
}
我想知道是否有一种方法可以根据我为变量名确定的结构从表单中获取值。具体问题在$question_$i = ...
。 我可以挽救这段代码还是需要重新考虑我命名这些变量的方式?谢谢!
最佳答案
要回答您的问题,您可以使用类似字符串的变量来引用
$var_1 = "hello";
echo ${"var_1"};
// or
$str = "var_1";
echo $$str;
但不要那样做
您想将这些值存储在一个数组中。
$question[$i] = $_POST['...'];
$is_correct[$i][$x] = $_POST['...'];
关于php - 使用 for() 循环创建唯一的 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7775440/