让我们从另一个方向来看这个。JS中的数据应该是什么样的?或者更确切地说,PHP 应该返回什么 JSON 才能使 JS 变得干净整洁。就像是:
var json = { // From PHP via AJAX
"questions_and_answers": [
{
"question": "What is the airspeed velocity of an unladen swallow?",
"answers": [
"11 meters per second",
"24 miles an hour",
"African or European?"
]
},
{
"question": "If a tree falls in an empty forest does it make a sound?",
"answers": [
"Unequivocally, yes.",
"Unequivocally, no.",
"It's all subjective."
]
}
]
};
for(var i = 0, j = json.questions_and_answers.length; i < j; i++) {
var question = json.questions_and_answers[i].question;
var answers = json.questions_and_answers[i].answers.join("\n");
alert(question + "\n" + answers);
}
现在,在 PHP 中会是什么样子?传递 json_encode 最简单的方法是嵌套数组,因为您没有使用问答对象或某种 ORM:
<?php
$questions_and_answers = array(
array(
"question" => "What is the airspeed velocity of an unladen swallow?",
"answers" => array(
"11 meters per second",
"24 miles an hour",
"African or European?"
)
),
array(
"question" => "If a tree falls in an empty forest does it make a sound?",
"answers" => array(
"Unequivocally, yes.",
"Unequivocally, no.",
"It's all subjective."
)
)
);
// Wrap in a parent object, assuming you're delivering to JS with via AJAX.
echo json_encode(array("questions_and_answers" => $questions_and_answers));
?>
因此,您的服务器端代码走在正确的轨道上,但您希望在循环访问数据库结果时填充一个空数组:
<?php
$thisquizid = $_POST['quizidvalue'];
$json_output = array();
for ($j = 0; $j < $questionrows; ++$j)
{
$questionresult = pg_fetch_array($questionquery);
$answerquery = pg_query($db_handle, "SELECT * FROM answer WHERE questionid = '$questionresult[0]'");
$answerrows = pg_num_rows($answerquery);
$json_output[$j] = array( "question" => $questionresult["text"], "answers" => array());
for ($i = 0; $i < $answerrows; ++$i)
{
$answerresult = pg_fetch_array($answerquery);
$json_output[$j]["answers"][] = $answerresult["text"];
}
}
echo json_encode(array("questions_and_answers" => $json_output));
?>