【问题标题】:Turning multiple PHP arrays into one array ready for conversion to Javascript将多个 PHP 数组转换为一个数组以准备转换为 Javascript
【发布时间】:2013-03-16 22:20:06
【问题描述】:

我正在使用 PHP 和 Javascript 创建一个多项选择问答游戏。问题可以有 2 到 6 个答案。我一直在使用下面代码中的 PHP 查询来获取测验问题的数组以及每个问题的答案。

我现在想在 Javascript 中使用这些数据,并且希望每次用户点击下一个问题时,都会显示一个问题和相应的答案。

我认为(但不确定)最好的方法是将数组组合成一个数组,其中问题数组包含答案数组,然后再转换为 javascript 数组。

这真的是我应该这样做的方式吗?如果是,我该怎么做?

$thisquizid = $_POST['quizidvalue'];
    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);  

        for ($i = 0; $i < $answerrows; ++$i)
            {
                $answerresult = pg_fetch_array($answerquery); 
            }

    }

【问题讨论】:

标签: php javascript arrays multidimensional-array


【解决方案1】:

让我们从另一个方向来看。 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 最简单的方法是嵌套数组:

<?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));

?>

【讨论】:

  • 谢谢,我先试试这个解决方案。
  • 祝你好运!刚刚修复了最终的代码块,请忽略之前的草率版本。将$questionresult["text"]$answerresult["text"] 中的text 替换为包含问题/答案文本的实际列名。
  • 非常感谢,我设法让它工作了,你的帮助非常有用,谢谢!
【解决方案2】:

当然,如果您不只想要 Javascript 中的所有内容,您可以这样做(即,它实际上是一个人们想要作弊的测验,因此您需要将答案存储在您的服务器上......)。

使用 AJAX 调用您的 PHP 页面,然后只返回您需要显示为变量的值,JSON 数组,等等......基本的 AJAX 调用将如下所示:

var xmlhttpMain=new XMLHttpRequest();
function changeContent(){
    xmlhttpMain.open("GET", true);
    xmlhttpMain.send(null);
    xmlhttpMain.onreadystatechange=function(){
    if (xmlhttpMain.readyState==4 && xmlhttpMain.status==200){
            newStuff=xmlhttpMain.responseText;//This is your JSON or Array that you create in the PHP file... 
            //Then run whatever code you want here
    }
}

在您的 PHP 文件中,只需使用“echo($someString);”把你的信息拍回JS土地...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-24
    • 2018-11-27
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2011-08-02
    相关资源
    最近更新 更多