使用for()循环创建唯一的PHP变量

Abu*_*e10 1 html php mysql sql forms

我有一个输入表单,允许我将新测验插入数据库.表单看起来像这样:

 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
    .
    .
    .
Run Code Online (Sandbox Code Playgroud)

不同的测验会有不同数量的问题(尽管每个问题总会有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>';
Run Code Online (Sandbox Code Playgroud)

所以,变量最终看起来像这样:

$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
...
Run Code Online (Sandbox Code Playgroud)

当我通过使用$ _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();
    }
Run Code Online (Sandbox Code Playgroud)

我想知道是否有办法根据我为变量名确定的结构从表单中获取值.具体问题在于$question_$i = .... 我可以抢救这个代码还是我需要重新思考我命名这些变量的方式? 谢谢!

hel*_*dre 5

要回答您的问题,您可以使用字符串来引用变量

$var_1 = "hello";
echo ${"var_1"};
// or
$str = "var_1";
echo $$str;
Run Code Online (Sandbox Code Playgroud)

但是不要这样做

您希望将这些值存储在数组中.

$question[$i] = $_POST['...'];
$is_correct[$i][$x] = $_POST['...'];
Run Code Online (Sandbox Code Playgroud)