从mysql打印数据时循环循环

时间:2012-05-30 18:35:45

标签: php foreach

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

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;
}

DATAS:

  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中的数据。

1 个答案:

答案 0 :(得分:2)

我能想到的最简单方法是提出两个问题:

  1. 请求question_id
  2. 排序的问题表单数据库列表
  3. 请求丢失列表1中所有问题的所有答案question_id
  4. 然后在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"
           ]
        }
    ]
    

    您应该避免单独查询DB以获取每个问题的答案。这有点浪费。