我必須從我的PHP編碼JSON文件中檢索JSON值問題PHP JSON值檢索錯誤
這是我PHP代碼:
$i = 0;
$qinfo = '';
$j=0;
$qry = "SELECT qid, q_title, q_question FROM questions WHERE qid = 1";
$result = mysql_query($qry);
$data = array();
while ($r = mysql_fetch_array($result)) {
$qinfo[$i]['qid'] = $r['qid'];
$qinfo[$i]['q_title'] = $r['q_title'];
$qinfo[$i]['q_question'] = $r['q_question'];
$qry2 = "SELECT aid, answer FROM answers WHERE qid=".$r['qid']." ";
$result2 = mysql_query($qry2);
while ($r2 = mysql_fetch_array($result2)) {
$qinfo[$j]["Ans"]["aid"] = $r2['aid'];
$qinfo[$j]["Ans"]["aid"] = $r2['answer'];
$j++;
}PHP
$i++;
}
echo json_encode($qinfo);
這是輸出JSON:
[{
"qid": "1",
"q_title": "This is first question title",
"q_question": "This is first question description",
"Ans": {
"aid": "26",
"answer": "This is first answer"
}
}, {
"Ans": {
"aid": "27",
"answer": "This is second answer"
}
}, {
"Ans": {
"aid": "28",
"answer": "This is third"
}
}]
- 這個JSON格式正確嗎?簡單地解釋:我得到1個問題的答案。
這裏是我試圖獲得結果的jQuery代碼。
$(document).ready(function() {
$.ajax({
type: "POST",
cache: false,
dataType:"json",
url: 'data.php',
success: function(data){
$('.show_divis').each(function (index, value){
var data_votes = '';
data_votes += '<div style="color:#000">'+data[index].q_title+'</div>';
data_votes += '<div style="color:#555">'+data[index].q_question+'</div>';
$(this).html(data_votes).fadeOut(300).fadeIn(400);
$('.show_divis2').each(function (index, value){
var data_votes2 = '';
data_votes2 += '<div style="color:#000">'+data[index].Ans.aid+'</div>';
data_votes2 += '<div style="color:#555">'+data[index].Ans.answer+'</div>';
$(this).html(data_votes2).fadeOut(300).fadeIn(400);
});
});
}
});
});
它會正確顯示的問題標題和描述。但只顯示1個答案?根據我的JSON文件有3個答案。我想在問題下顯示3個答案。我可以改變我的JSON格式嗎? 在此先感謝!
您所使用的格式肯定是不方便在頂層ARR的位置ay確定答案屬於的問題。將所有答案都捆綁在一個數組中,將它們歸屬於它們的問題會更合乎邏輯。然後你可以在JavaScript中使用2個嵌套循環,就像你已經在PHP中做的一樣。 – jeroen
嗨,感謝您的回覆。 HTML部分只有2周的div的類
–