我使用此代碼將問題與選項一起分組。將數組插入數據庫
<?php
$entries = preg_split('/(?=[a-z\d]+\.(?!\d))/', $str, -1, PREG_SPLIT_NO_EMPTY);
$questions = array();
$currentQuestion = null;
$id = 0;
foreach($entries as $entry) {
if(is_numeric(substr($entry, 0, 1)) === true) {
$currentQuestion = $entry;
$questions[$entry] = array();
$id++;
// echo "INSERT INTO question (id, q_name) VALUES ($id, $currentQuestion)"."<br>";
// mysqli_query($con, "INSERT INTO question (id, q_name) VALUES (NULL, '$currentQuestion')");
continue;
}
// mysqli_query($con, "INSERT INTO answers (id, choices, question, correct) VALUES (NULL, 'choices', $id , 0);");
// echo "INSERT INTO answers (id, choices, question, correct) VALUES (NULL, 'choices', $id , 'stuff')"."<br>";
$questions[$currentQuestion][] = $entry;
}
這是數組的結果。
Array
(
[1. What is love?] => Array
(
[0] => a. Haddaway
[1] => b. Haxxaway
[2] => c. Hassaway
[3] => d. Hannaway
)
[2. What is love? ] => Array
(
[0] => a. Haddaway
[1] => b. Haxxaway
[2] => c. Hassaway
[3] => d. Hannaway
)
[3. What is love 1.1? ] => Array
(
[0] => a. Haddaway
[1] => b. Haxxaway
[2] => c. Hassaway
[3] => d. Hannaway
)
[4. What is love? ] => Array
(
[0] => a. Haddaway
[1] => b. Haxxaway
[2] => c. Hassaway
[3] => d. Hannaway
)
)
,這是我的數據庫結構:表answers
question
列是從questions
表的主鍵,這將決定哪些問題選擇屬於...
questions
+-------+--------------------------+
| id | q_name |
+-------+--------------------------+
| 1 | 1.) What is foo? |
| 2 | 2.) What is foo? |
+-------+--------------------------+
answers
+-------+-------------+-----------------------+
| id | choices | question | correct |
+-------+-------------+-----------------------+
| 1 | a. foo1 | 1 | 0 |
| 2 | b. foo2 | 1 | 0 |
| 3 | c. foo3 | 1 | 1 |
| 4 | a. foo3 | 2 | 0 |
| 5 | b. foo2 | 2 | 1 |
| 6 | c. foo1 | 2 | 0 |
+-------+-------------+-----------------------+
我設法插入問題db,但我有麻煩插入選擇,因爲我很困惑我應該怎麼做$questions
爲了得到選擇...
任何建議(S)會做!
** 1)**儘量不要在循環中運行查詢,而是在循環內部構建它並在循環之後執行它。 ** 2)**請粘貼數據庫表的結構; '答案'和'問題'('SHOW CREATE TABLE answers;')? – 2015-02-11 14:19:20
哦,真抱歉...好吧,我會編輯它,非常感謝! – yowza 2015-02-11 14:20:39
@ʰᵈˑ我更新了我的問題,我希望這已經夠透徹了。 – yowza 2015-02-11 14:40:23