我有一个数据库表,其中有2个表,
每个问题都有多个答案
我正在尝试将所有问题和答案放在一个数组中。以下代码正常运行。我在foreach中使用for循环,如果有一点改进下面的代码,那将非常有帮助
$sql = "SELECT * FROM questions AS q LEFT JOIN answers AS a ON q.question_id=a.question_id WHERE q.question_id=a.question_id AND category_id =:category_id";
$stmt = $this->db->conn_id->prepare($sql);
$stmt->bindValue('category_id',$category_id, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $d){
$qid = $d['question_id'];
$q[$qid]['question'] = $d['question'];
$q[$qid]['answers'][] = $d['answers'];
}
/*
Checking the output, for send the $data when this function is called
foreach($q as $id => $val){
echo $val['question'] .'<br>';
for($i=0; $i<4; $i++){
echo $val['answers'][$i];
}
}
*/
答案 0 :(得分:3)
我会这样做(PSEUDO CODE):
$questions = get all questions
$answers = get all answers
$my_questions = array();
foreach ($questions as $q) {
$my_questions[$q['id']] = array(
'question' => $q['question'],
'answers' => array()
)
}
foreach ($answers as $a) {
$my_questions[$a['question_id']]['answers'][$a['answer_id']] = $a['answer'];
}
结果如下:
[
39 => [
'question' => "Who am i?",
'answers' => [
53 => "I don't know",
54 => "Who cares?"
]
]
]
我敢打赌,这比加入SQL中的两个表要快。也更容易处理,也无法从服务器获取任何额外数据。