2011-10-15 72 views
1

我有一個輸入表單,允許我將新測驗插入到數據庫中。形式看起來是這樣的:用於()循環創建獨特的PHP變量

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 = ...我可以挽救這段代碼嗎?還是需要重新思考我命名這些變量的方式?謝謝!

回答

5

要回答你的問題,你可以參考變量與字符串像

$var_1 = "hello"; 
echo ${"var_1"}; 
// or 
$str = "var_1"; 
echo $$str; 

但不這樣做,

你想將這些值存儲在陣列中。

$question[$i] = $_POST['...']; 
$is_correct[$i][$x] = $_POST['...']; 
+1

注意不要造成大量不必要的變量。 –

0

你爲什麼不把你的輸入命名爲數組?

<input type='text' name='correct[]'/> 

然後你用POST發送表單,$ _POST ['correct']將是一個數組。