javascript - 循环遍历php mysql中的json数据来获取javascript函数

标签 javascript php mysql json

我有一个来自 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/

相关文章:

javascript - 在不链接回调函数的情况下从 Node JS GET 请求访问数据

javascript - 使用 css 和 javascript 隐藏 div

php - 如何捕捉 ZF2 Controller 中的异常?

mysql - 按类别选择行

对多对多外连接的mysql查询产生重复

Javascript Web 应用程序无法在 IE 中运行

javascript - 克隆最后一列并将其添加到同一个表中 - jQuery

php - 将数据从 View 传递到 Controller (Zend)

php - 在 Laravel 上手动登录到与默认连接不同的连接

mysql - (My)SQL - 根据表 B 填充表 A 中的值