基本上,我有三张桌子。我有一个项目表、一个问题表和一个答案表。一个项目可以有很多问题,一个问题可以有很多答案。在问题 ID 上使用 PDO 和 LEFT JOIN,我如何将带有答案的评论转换为多维数组,以便结构如下所示:
[Question] => Array
(
[id] => 1
[question] => 'Random Question'
[askedBy] => 123
[answer] => Array
(
[0] => Array
(
[id] => 1
[answer] => 'An Answer'
[answeredBy] => 123
)
[1] => Array
(
[id] => 1
[answer] => 'Another Answer'
[answeredBy] => 123
)
)
)
最终代码(返回我想要的)
$questions = array();
$questionCounter = 0;
$questionID = NULL;
$STH = $DBH->query("SELECT `project_question`.`id` AS question_id, `project_question`.`question`, `project_question`.`userID` AS askedBy,
`project_question`.`created` AS question_created, `project_answer`.`id` AS answer_id,
`project_answer`.`answer`, `project_answer`.`userID` AS answeredBy,
`project_answer`.`accepted`, `project_answer`.`created` AS answer_created
FROM `project_question`
LEFT JOIN `project_answer`
ON `project_question`.`id` = `project_answer`.`questionID`
WHERE `project_question`.`projectID` = $args[0]
AND `project_question`.`projectPhase` = 2");
while($row = $STH->fetch(PDO::FETCH_ASSOC)){
if($row['question_id'] !== $questionID){
$questions[$questionCounter] = array(
'id' => $row['question_id'],
'question' => $row['question'],
'userID' => $row['askedBy'],
'created' => $row['question_created'],
'answers' => array()
);
array_push($questions[$questionCounter]['answers'],
array(
'id' => $row['answer_id'],
'answer' => $row['answer'],
'userID' => $row['answeredBy'],
'accepted' => $row['accepted'],
'created' => $row['answer_created']
));
$questionCounter++;
$questionID = $row['question_id'];
} else {
array_push($questions[$questionCounter - 1]['answers'],
array(
'id' => $row['answer_id'],
'answer' => $row['answer'],
'userID' => $row['answeredBy'],
'accepted' => $row['accepted'],
'created' => $row['answer_created']
));
}
}