В принципе, у меня есть три таблицы. У меня есть таблица проектов, таблица вопросов и таблица ответов. У проекта может быть много вопросов, и у вопроса может быть много ответов. Использование ПДО и LEFT JOIN по вопросу ID, как я могу включить комментарии с ответами в многомерный массив так, что структура будет выглядеть следующим образом:PHP 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']
));
}
}
Возможно, вам будет лучше с несколькими запросами. Используйте один, чтобы получить вопросы, затем еще один, чтобы получить ответы на каждый вопрос. –
Что предлагает @RocketHazmat, не является хорошей альтернативой, потому что вы значительно увеличиваете нагрузку на MySQL. Это может привести к увеличению времени отклика, особенно. если база данных и веб-сервер не находятся на одном сервере. – Gajus