dongya0914 2016-05-29 13:10
浏览 21

具有多个列的API php转到一个id

In my database I have multiple columns like this

Questions

question one with questionID 1
question two with questionID 2
...

Answers

answer one with questionID 1
answer two with questionID 1
answer one with questionID 2
answer two with questionID 2

To retrieve them I usually works as the example below:

$sql = "SELECT * FROM Questions LEFT JOIN Answers ON Questions.questionID = Answers.questionID";

getting this outcome:

[{
    "questionID": "1",
    "question": "Test Question",
    "potID": "1",
    "optionID": "1",
    "optionValue": "answer 1",
    "isCorrect": "0"
}, {
    "questionID": "1",
    "question": "Test Question",
    "potID": "1",
    "optionID": "2",
    "optionValue": "answer 2",
    "isCorrect": "1"
}]

How can I get the data as following

[{
    "questionID": "1",
    "question": "Test Question",
    "potID": "1"
{Answers: [
    "optionID": "1",
    "optionValue": "answer 1",
    "isCorrect": "0"
}, {
    "optionID": "2",
    "optionValue": "answer 2",
    "isCorrect": "1"
]}
}]
  • 写回答

1条回答 默认 最新

  • donglie7778 2016-05-29 13:46
    关注

    I suggest you to use cycle inside another cycle to collect all answer to specific question. How I usually do this using PHP:

    $questions = [
        ['questionID' => 1, 'question' => 'What is my name?', 'answers' => []]
    ];
    
    $answers = [
        ['answerID' => 1, 'value' => 'John', 'questionID' => 1, 'isCorrect' => 1],
        ['answerID' => 2, 'value' => 'Paul', 'questionID' => 1, 'isCorrect' => 0]
    ];
    
    foreach ($questions as $question) {
        foreach ($answers as $answer) {
            if ($answer['questionID'] == $question['questionID']) {
                $question['answers'][] = $answer;
            }
        }
    }
    
    // output should be something like this
    [
        'questionID' => 1, 'question' => 'What is my name?', 'answers' => [
            ['answerID' => 1, 'value' => 'John', 'questionID' => 1, 'isCorrect' => 1],
            ['answerID' => 2, 'value' => 'Paul', 'questionID' => 1, 'isCorrect' => 0]
        ]
    ]
    

    You need to make something similar to this using your language.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计