Cri*_*ter 5 php mysql jquery select multidimensional-array
我刚刚开始学习更高级的SQL和PHP,我真的在努力寻找如何查询我的数据库以进行我正在构建的测验.
最后,我试图返回一个具有以下结构的json对象,它给出了一个问题列表和所有可能的答案作为多维数组:
{
"questions":
[
{
"question": "question text here",
"answers":
[
{ "answer": "answer text here", "points": 10 },
{ "answer": "answer text here", "points": 20 },
{ "answer": "answer text here", "points": 30 },
{ "answer": "answer text here", "points": 40 }
]
},
{
"question": "question text here",
"answers":
[
{ "answer": "answer text here", "points": 10 },
{ "answer": "answer text here", "points": 20 },
{ "answer": "answer text here", "points": 30 },
{ "answer": "answer text here", "points": 40 }
]
}
]
{
Run Code Online (Sandbox Code Playgroud)
...来自我的以下结构的mySQL表:
测验
id | title
1 | quiz title here
Run Code Online (Sandbox Code Playgroud)
quiz_question
id | quiz_id (FK) | question_text
1 | 1 | question text here
2 | 1 | question text here
Run Code Online (Sandbox Code Playgroud)
quiz_answer
id | quiz_question_id (FK) | answer_text | points
1 | 1 | answer text here | 10
2 | 1 | answer text here | 20
3 | 1 | answer text here | 30
4 | 1 | answer text here | 40
Run Code Online (Sandbox Code Playgroud)
...使用以下外键:
quiz_question.quiz_id is FK to quiz.id
quiz_answer.quiz_question_id is FK to quiz_question.quiz_id
Run Code Online (Sandbox Code Playgroud)
...使用以下PHP(以最简单的形式,目前只返回我的问题):
//query the db
$query = mysql_query("
SELECT quiz_question.question_text
FROM quiz_question
JOIN quiz ON quiz.id = quiz_question.quiz_id
WHERE quiz.id = 1;
");
$numrows = mysql_num_rows($query);
for ($i = 0; $i < $numrows; $i++) {
$row = mysql_fetch_assoc($query);
$quiz_data[$i] = array("question" => $row["question_text"]);
}
//echo JSON to page
$response = $_GET["jsoncallback"] . "(" . json_encode($quiz_data) . ")";
echo $response;
Run Code Online (Sandbox Code Playgroud)
...并在我的JavaScript中使用jQuery的$ .getJSON(),它从我的PHP获取了一个JSON格式的对象,它让我回到了以下内容:
[
{"question":"question text here"},
{"question":"question text here"}
]
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,如何编写我的SQL和PHP来创建一个像上面那样的多维数组而不是像我现在要回来的单个数组?我需要弄清楚如何将问题和所有相关答案都包含在一个多维数组中.
你不能完全用mysql检索一个多维数组(至少据我所知).你将不得不做一些PHP处理.这听起来并不太疯狂.
首先,更新您的查询通过连接选择在同一时间的答案quiz_answers
上quiz_questions
使用的问题ID.然后,在你的循环中:
$quiz = array();
while ($row = mysql_fetch_assoc($result)) {
// you don't need to check num_rows
// fetch_assoc returns false after the last row, so you can do this
// which is cleaner
if (!isset($quiz[$row['question_id'])) {
$quiz[$row['question_id']] = array(
'question' => $row['question_text']
, 'answers' => array()
);
}
$quiz[$row['question_id']]['answers'][] = $row['answer_text'];
}
$full = json_encode(array('questions' => $quiz'));
Run Code Online (Sandbox Code Playgroud)
这将为您提供json编码后所需的数组.
请注意,您最终会为每个答案选择一次问题文本/ ID,这是低效的.你可以GROUP_CONCAT
在答案上使用,但上面几乎完全相同,你只需要分开答案字符串.
我还建议你使用PDO
或其他一些包装mysql_*
.