2011-05-12 72 views
1

我有這種形式,我需要提交一些隱藏值的問題,並將它們連接在一起。表單提交處理和生成

我現在追加名稱與問題的ID,然後添加_然後答案的數量。

<form> 
    <span>1:Question goes here </span> 
    <input type=hidden name=t_1 value=10> 
    <input type=hidden name=f_1 value=20> 
    <input type=checkbox name=a1_1>value1 
    <input type=checkbox name=a1_2>value2 
    <input type=checkbox name=a1_3>value3 
    <span>2:Question goes here </span> 
    <input type=hidden name=t_2 value=40> 
    <input type=hidden name=f_2 value=20> 
    <select name=a2_1> 
     <option>blah</option> 
     <option>etc</option> 
    </select> 
</form> 

在服務器端,我爆炸提交的領域和把它們放在一起:

foreach ($_POST as $var => $val) { 
    switch ($var[0]) { 
     case "a" : 
      $b = substr($var, 1); // remove first char to get number following 
      $pos = strpos($b, "_"); 
      if ($pos !== false) { 
       $i = explode("_", $b); // separating question number from choice number (for multi select questions) 
       $answer[$i[0]][] = $val; 
       break; 
      } 
      else { 
       $answer[$b][] = $val; 
       break; 
      } 
     case "t" : 
      $b = substr($var, 1); 
      $target[$b] = $val; 
      break; 
    } 
} 

有沒有更好的方式來做到這一點?

回答

2

你能說出你的標籤以下列方式:

<input name="question[1][answer]" type="text" value="someValue" /> 

這將爲你的問題陣列,您可以通過他們itterate,而無需爆炸或任何串。

1

您可以使用

f[] or f[1], f[2] 

這樣做,$ _ POST將包含數組。