我想创建简单的民意调查系统。我有两个问题和两个答案。第一个问题有两个答案,但第二个问题没有任何答案。从某种意义上说,我想得到:
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中的数据。
答案 0 :(得分:2)
我能想到的最简单方法是提出两个问题:
question_id
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"
]
}
]
您应该避免单独查询DB以获取每个问题的答案。这有点浪费。