2015-04-21 84 views
-3

我有一個形式類似這樣PHP:獲取表單輸入

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

*用戶可以添加或刪除動態輸入。

我已經厭倦了

foreach($_POST['question_title'] as $question_key=>$question_title){ 
    echo $question_title.'<br>'; 
    foreach($_POST['answer_title'] as $answer_key=>$answer_title){ 
     echo $answer_title.'<br>'; 
    } 
} 

,但我得到

question 1 
answer 1 
answer 2 
answer 3 
answer 1 
answer 2 

question 2 
answer 1 
answer 2 
answer 3 
answer 1 
answer 2 

,但我想代碼輸出

question 1 
answer 1 
answer 2 
answer 3 


question 2 
answer 1 
answer 2 

*結果是輸入值。

在此先感謝。

更新:感謝downvote,這是一個偉大的社區。我經過許多研究併發布了我的代碼後來到這裏。謝謝你的stackoverflow。

+0

這種分組也是可能的,其中一個可能的答案可能取決於你如何動態創建問題集,你也可以發佈該部分 – Ghost

+0

@鬼動態問題集與上面的代碼相同,可以添加多達問答。沒有編號索引 – bekman

回答

0

問題/答案具有相同的名稱。你必須給他們不同的名字,否則PHP將無法告訴你哪些答案與哪些問題有關。

當您添加一個提問/回答,請確保它的名字是沿着 「answer[question_id/index][]」 東西線或 「question[id]

1

嘗試:

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

然後

foreach($_POST['question_title'] as $question_key=>$question_title){ 
    echo $question_title.'<br>'; 
    foreach($_POST['answer_title'][$question_key] as $answer_key=>$answer_title){ 
     echo $answer_title.'<br>'; 
    } 
} 
+0

我也是這樣做的,但是你需要創建一個動態的javascript函數來創建添加新的行,它引入了編號索引 – Ghost

+0

我試過同樣的東西,不想每次都更新整個索引輸入被刪除 – bekman