基本上,我有三张桌子。我有一个项目表,一个问题表和一个答案表。一个项目可以有很多问题,一个问题可以有很多答案。在问题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']
));
}
}
答案 0 :(得分:0)
在一个查询中,您可以请求所有答案,加入问题并将项目加入问题。
$projects = array()
foreach ($rows as $row)
if (!isset($projects[$row->project_id])) { $projects[$row->project_id] = array('col1' => $row->col1,'questions' => array()); }
if (!isset($projects[$row->project_id]['questions'][$row->question_id])) { $projects[$row->project_id]['questions'][$row->question_id] = array('col2' => $row->col2,'answers' => array()); }
$projects[$row->project_id]['questions'][$row->question_id]['answers'][$row->answer_id] = array('col3' => $row->col3);
但是正如您所理解的那样,您将在该查询中获得许多无用的信息。您可以使用一个查询,仅获取项目,遍历它们,在每个周期中将数据添加到数组并再次查询以获取具有特定project_id的问题,迭代它们,在每个周期中将数据添加到数组并再次查询以获得答案具有特定的question_id,迭代它们,并将数据添加到数组。
但是如果我重新考虑这个问题,我认为MySQL的运行速度比PHP快,即使返回一堆无用的数据(我的意思是,重复关于项目和问题的数据)和1个查询与来自一个客户端的50个查询相比要好得多,所以我建议更好地使用第一种方法。
如果没有关于数据库表和列的更多信息,除了伪代码算法之外,你不会得到任何其他信息。
编辑:可能的MySQL选择查询:
SELECT
a.id answer_id, a.answer, a.answeredBy,
q.id question_id, q.question, q.askedBy,
p.id project_id, p.title
FROM answer a
LEFT JOIN question q ON q.id = a.question_id
LEFT JOIN project p ON p.id = q.project_id
表结构