我正在进行测验,我必须参加表格:问题和答案。
我遇到了sql-query
的问题现在我得到一个包含每个答案的问题的JSONObject,如何在每个问题中获得一个包含与该问题相关的所有答案的对象?因此,当我读取json数据时,我可以获取包含第一个答案的第一个对象以及与该问题相关的答案。
编辑:php代码,整个JSON部分并不重要,因为如果我得到正确的数组,那么JSON也是正确的。$query = "
SELECT * FROM Questions
LEFT JOIN Answers ON Questions.questionID=Answers.questionID
UNION
SELECT * FROM Questions
RIGHT JOIN Answers ON Questions.questionID=Answers.questionID
LIMIT 10";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
$json = json_encode($array);
echo $json;
答案 0 :(得分:0)
我不确定给出正确结果的查询
你可以使用
$query = "SELECT * FROM Questions
LEFT JOIN Answers ON Questions.questionID=Answers.questionID ";
而不是联合,但是对于你的查询,这应该给出你期望的东西..
$query = "
SELECT * FROM Questions
LEFT JOIN Answers ON Questions.questionID=Answers.questionID
UNION
SELECT * FROM Questions
RIGHT JOIN Answers ON Questions.questionID=Answers.questionID
LIMIT 10";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['questionID']]['answers'][$row['answerID']] = $row['answer'];
$array[$row['questionID']]['questionID'] = $row['questionID'];
$array[$row['questionID']]['question'] = $row['question'];
$array[$row['questionID']]['category'] = $row['category'];
$array[$row['questionID']]['correct'] = $row['correct'];
}
$json = json_encode($array);
echo $json;