讓我們從另一個方向來看這個。 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));
?>
我建議你在[Code Review](http://codereview.stackexchange.com/)上提問這個問題。 – 2013-03-16 22:38:12