我正在尝试将数据库查询的输出显示为多选测验程序的特定JSON输出。我调试了脚本,它工作正常,但我需要将多维数组的结果显示为下面显示的JSON输出格式:
{"childItems":[
{"itemId":"question1", "itemType":"BT_questionItem",
"questionText":"What is the capital city of Nevada?",
"correctAnswerText":"Carson City",
"incorrectText1":"Las Vegas",
"incorrectText2":"Reno",
"incorrectText3":"Tahoe",
"imageURLSmallDevice":"http://www.mywebsite.com/quizImage1.png",
"imageURLLargeDevice":"http://www.mywebsite.com/quizImage1.png"
},
{"itemId":"question2", "itemType":"BT_questionItem",
"questionText":"What is the capital city of California?",
"correctAnswerText":"Sacramento",
"incorrectText1":"Modesto",
"incorrectText2":"Monterey",
"incorrectText3":"Los Angeles",
"imageURLSmallDevice":"http://www.mywebsite.com/quizImage2.png",
"imageURLLargeDevice":"http://www.mywebsite.com/quizImage2.png"
}
]
}
现在这里是我的代码(我留在调试行中供其他人使用,如果他们也需要它们):
<?php
if(!$connection)
{
die('Unable to connect to database server.');
}
if(!mysql_select_db($dbname, $connection))
{
die('Unable to select database.');
}
//Query for questions/answers
$question_table="wp_mtouchquiz_question";
$answer_table="wp_mtouchquiz_answer";
$query = "SELECT q.id, q.question, a.answer
FROM {$question_table} q
JOIN {$answer_table} a ON q.ID = a.QUESTION_ID
WHERE q.quiz_id = 1
ORDER BY question_id ASC, correct DESC";
$result = mysql_query($query);
## DEBUGGING LING ##
echo "Query: {$query}<br>
Num Records " . mysql_num_rows($result) . "<br><br>\n";
if(!$result)
{
//die ('Unable to get questions.'); //Comment out to debug
die("Query: $query<br>Error: " . mysql_error());
}
//Populate results into multi-dimensional array
$questions = array();
while($row = mysql_fetch_assoc($result))
{
## DEBUGGING LING ##
echo implode(" : ", $row) . "<br>\n";
$qID = $row['id'];
if(!isset($questions[$qID]))
{
$questions[$qID] = array(
'question' => $row['question'],
'question_id' => $qID,
'answers' => array()
);
}
$questions[$qID]['answers'][] = $row['answer'];
}
## DEBUGGING LING ##
echo "Array before randomizing:<br><pre>" . print_r($questions, true) . "</pre><br>\n";
//Randomize the questions and answers
shuffle($questions);
foreach($questions as &$question)
{
unset($question['answers'][rand(1, 4)]); // <== This will remove one of the incorrect answers before randomizing
shuffle($question['answers']);
}
## DEBUGGING LING ##
echo "Array after randomizing:<br><pre>" . print_r($questions, true) . "</pre><br>\n";
//NOW output the results in the needed JSON string
?>