我有一个来自 php 的 json 数据,它工作得很好。 我现在想要的是,我希望我的 json 数据像下面的 javascript 函数中的代码一样。 我想迭代并获取类似的数据,如 javascript 代码中的对象。 我如何获得它。
$json_array = array();
$sql = "SELECT id, instructions, quiz_question, correct, wrong, wrong1, wrong2 FROM student_quiz WHERE subject = 'SOCIAL STUDIES' AND type = 'challenge'";
$results = $pdo->query($sql);
$results->setFetchMode(PDO::FETCH_ASSOC);
while($row = $results->fetch()) {
$json_array['quizlist'][] = $row ;
}
?>
<script type='text/javascript'>
(function() {
var questions = [{
question: "What is 3*6?",
choices: [3, 6, 9, 12, 18],
correctAnswer: 4
}, {
question: "What is 8*9?",
choices: [72, 99, 108, 134, 156],
correctAnswer: 0
}, {
question: "What is 1*7?",
choices: [4, 5, 6, 7, 8],
correctAnswer: 3
}, {
question: "What is 8*8?",
choices: [20, 30, 40, 50, 64],
correctAnswer: 4
}];
最佳答案
要从数据库数据输出 JSON,如果其中一个数据无法进行更多调整和自定义,最好在数据之间进行映射。
为了在 PHP 中输出映射的 JSON 数组,有一个函数 json_encode()
。在下面的示例中,还使用了 shuffle()
来随机化选择。
// ...
$sql = "SELECT id, instructions, quiz_question, correct, wrong, wrong1, wrong2 FROM student_quiz WHERE subject = 'SOCIAL STUDIES' AND type = 'challenge'";
$results = $pdo->query($sql);
$results->setFetchMode(PDO::FETCH_ASSOC);
$json = [];
while($row = $results->fetch()) {
$choices = [
$row['correct'],
$row['wrong'],
$row['wrong1'],
$row['wrong2'],
];
// shuffle the current choices so the 1st item is not always obviously correct
shuffle($choices);
$json[] = [
'question' => $row['question'],
'choices' => $choices,
'correctAnswer' => $row['correct'],
];
}
echo json_encode($json);
关于javascript - 循环遍历php mysql中的json数据来获取javascript函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52240175/