2016-09-19 52 views
1

我在写一个PHP脚本,可以以下面的格式返回一个JSON文件。我想通过从我的数据库表中获取数据来创建这个结构。我正在使用SlickQuiz插件,并且很难在问题对象内部创建一个对象数组(即选项),该对象数组又被作为数组包含在内。在PHP中返回复杂的JSON结构

{ 
    "info": { 
     "name": "This is Exam name", 
     "main": "Find out with this super crazy knowledge", 
     "results": "Get ready", 
     "level1": "Result Poor", 
     "level2": "Result Average", 
     "level3": "Result Good", 
     "level4": "Result Very Good", 
     "level5": "Result Great" 
    }, 
    "questions": [ 
      "q": "Which is the letter A in the English alphabet?", 
      "a": [ 
       {"option": "8",  "correct": false}, 
       {"option": "14",  "correct": false}, 
       {"option": "1",  "correct": true}, 
       {"option": "23",  "correct": false} 
      ], 
      "correct": "This is correct", 
      "incorrect": "It's the first letter of the alphabet." 
     }, 
     { 
      "q": "Eureka Which of the following best represents your preferred breakfast?", 
      "a": [ 
       {"option": "Bacon and eggs",    "correct": false}, 
       {"option": "Fruit, oatmeal, and yogurt", "correct": true}, 
       {"option": "Leftover pizza",    "correct": false}, 
       {"option": "Eggs, fruit, toast, and milk", "correct": true} 
      ], 
      "select_any": true, 
      "correct": "<p><span>Nice!</span> Your cholestoral level is probably doing alright.</p>", 
      "incorrect": "<p><span>Hmmm.</span> You might want to reconsider your options.</p>" 
     }, 
     { 
      "q": "Eureka Where are you right now? Select ALL that apply.", 
      "a": [ 
       {"option": "Planet Earth",   "correct": true}, 
       {"option": "Pluto",     "correct": false}, 
       {"option": "At a computing device", "correct": true}, 
       {"option": "The Milky Way",   "correct": true} 
      ], 
      "correct": "<p><span>Brilliant!</span> You're seriously a genius, (wo)man.</p>", 
      "incorrect": "<p><span>Not Quite.</span> You're actually on Planet Earth, in The Milky Way, At a computer. But nice try.</p>" 
     }, 
     { 
      "q": "How many Eureka of rain does Michigan get on average per year?", 
      "a": [ 
       {"option": "149", "correct": false}, 
       {"option": "32",  "correct": true}, 
       {"option": "3",  "correct": false}, 
       {"option": "1291", "correct": false} 
      ], 
      "correct": "<p><span>Eureka bananas!</span> I didn't actually expect you to know that! Correct!</p>", 
      "incorrect": "<p><span>Fail.</span> Sorry. You lose. It actually rains approximately 32 inches a year in Michigan.</p>" 
     }, 
     { 
      "q": "Is Earth bigger than a basketball?", 
      "a": [ 
       {"option": "Yes", "correct": true}, 
       {"option": "No",  "correct": false} 
      ], 
      "correct": "<p><span>Eureka Job!</span> You must be very observant!</p>", 
      "incorrect": "<p><span>ERRRR!</span> What planet Earth are <em>you</em> living on?!?</p>" 
    ] 
} 

下面是我试图使用PHP生成这个。

function generateJSON($pdo){ 
    $response = array(); 
      $response["error"] = false;   
      $response["questions"] = array(); 

    $stmt = $pdo->prepare("SELECT * FROM questions"); 
    $stmt->execute(); 
    $result= $stmt->fetchAll(); 
    if($stmt->rowCount() > 0){ 
    foreach($result as $row) { 
     $tmp = array(); 
     $tmp["id"] = $row["id"]; 
     $tmp["q"] = $row["question"]; 
     $tmp["correct"] = $row["question"]; 
     $tmp["incorrect"] = $row["subject_id"]; 
     $tmp["status"] = $row["level_id"]; 

     //Fetching the options 
     $stmt2 = $pdo->prepare("SELECT * FROM question_options WHERE question_id = ".$tmp["id"]); 
     $stmt2->execute(); 
     $opt_result= $stmt2->fetchAll(); 
     foreach($opt_result as $opt_row) { 
     $option = array(); 
     $option["option"] = $opt_row["option_text"]; 
     $option["correct"] = $opt_row["is_correct"] ==1; 
     array_push($response["questions"], $option); 
     } 
     //End of fetching options for this question 

     array_push($response["questions"], $tmp); 
    } 
    } 
      echoRespnse(200, $response); 
} 
+0

我有些新来这...不知道如果我需要创建一个类似的PHP类,然后将其编码为json。但任何示例或建议都非常感谢。 –

+0

创建一组实现'JsonSerializable'接口并在复杂对象上使用'json_encode'的类是面向对象的方法来完成这一任务,但是是可选的。制作一个封装你需要的所有信息的关联数组可能更简单。 – apokryfos

回答

0

正如@apokryfos在评论中提到的那样,您真的应该考虑让代码更加模块化。最常见的,可以说是最简单的方法就是使用类。
的你怎么能构建这个一个简单的例子:这一点需要

class Quiz { 
    private $questions; 
    public function addQuestion (Question $question) 
    public function addGrade ($title, $score) 
    public function serialize() 
} 

class Question { 
    private $text; 
    private $alternatives = array(); 
    private $correctString; 
    private $incorrectString; 
    public function setText ($text) 
    public function addAlternative ($text, $correct) 
    public function serialize() 
} 

填充,并添加您需要的一些缺失的方法。确保您在serialize()函数中返回必要的数据,以便您可以使用它们构建请求的数组。

一旦做到这一点,那么你可以做一些与此类似,使用INNER JOIN把所有的记录在一个查询:

// Generate the quiz and set all of its properties. 
$quiz = new Quiz(); 

while ($row = $res->fetch_row()) { 
    if ($row['question_id'] != $oldID) { 
     // Save the old (completed) question to the quiz. 
     $quiz->addQuestion ($question); 

     // Used to detect when we get to a new question. 
     $oldID = $row['question_id']; 

     $question = new Question(); 

     // Add the question details here. 
     $question->addTitle(); 
     ...... 
    } 

    // Each question has at least one alternative. 
    $question->addAlternative ($row['alt'], $row['correct']}; 
} 

// We need to ensure that we've added the last question to the quiz as well. 
$quiz->addQuestion ($question); 

$data = json_serialize ($quiz->serialize());