0

我想创建简单的投票系统。我有两个问题和两个答案。第一个问题有两个答案,但第二个问题没有任何答案。从某种意义上说,我想得到:

First question?
Answer1
Answer2

Second question?

但我越来越

First question?
Answer1
Answer2

Second question?
Answer1 
Answer2

第二个问题不需要有 Answer1 和 Answer2(与第一个问题的答案相同,但我在 mysql 中有两个答案)。

还有我的 foreach 循环。我需要如何更改循环?

foreach($questions->getQuestion($_GET["category"]) as $data) // Questions
{
    echo $data["question"] . "<br/>";
    foreach($questions->getAnswer($data["id"]) as $answers) // Answers
    {
        echo $answers["answer"] . "<br/>"; // This needn't print data to below of Second Question
    }
}

职能:

public function getQuestion( $cat )
{
    if(empty($cat))
    {
        header("location:index.php");
    }

    $this->sql = "SELECT * FROM questions WHERE category='" . $cat . "'";
    $data = parent::getData();
    return $data;
}

public function getAnswer( $question )
{
    $this->sql = "SELECT * FROM answers WHERE questions='" . $question .  "'";
    $data = parent::getData();
    return $data;
}

数据:

  Array
(
    [0] => Array
        (
            [id] => 1
            [soru] => First Question
            [kategori] => 1
        )

    [1] => Array
        (
            [id] => 2
            [soru] => Second Question
            [kategori] => 1
        )

)
Array
(
    [0] => Array
        (
            [id] => 1
            [soru] => First Question
            [kategori] => 1
        )

    [1] => Array
        (
            [id] => 2
            [soru] => Second Question
            [kategori] => 1
        )

    [2] => Array
        (
            [id] => 1
            [cevap] => Answer1
            [sorular] => 1
        )

    [3] => Array
        (
            [id] => 2
            [cevap] => Answer2
            [sorular] => 1
        )

    [4] => Array
        (
            [id] => 1
            [cevap] => Answer1
            [sorular] => 1
        )

    [5] => Array
        (
            [id] => 2
            [cevap] => Answer2
            [sorular] => 1
        )

)

注意:这些数据只是示例。这些是mysql中的数据。

4

1 回答 1

2

我能想到的最简单的方法是有两个查询:

  1. 请求按顺序排列的问题表单数据库列表question_id
  2. 要求丢失列表 1 中所有问题的所有答案。按顺序排列question_id

然后在 php 方面,您匹配每个问题的答案。这将是一个循环,因为问题和答案都已排序,无需“后退”。

你最终会得到这样的结构:

list = [
    {
       question: "Lorem ipsum",
       answers: [
          "answer number one",
          "answer number two"
       ]
    },
    {
       question: "Cogito ergo sum",
       answers: [
          "answer number one",
          "answer number two"
          "answer number three",
          "answer number four"
       ]
    }
]

您应该避免分别向数据库查询每个问题的答案。有点浪费

于 2012-05-30T18:42:19.760 回答