简体   繁体   English

PHP PDO左连接多维数组

[英]PHP PDO LEFT JOIN Multidimensional Array

Basically, I have three tables. 基本上,我有三个表。 I have a projects table, a questions table and an answers table. 我有一个项目表,一个问题表和一个答案表。 A project can have many questions and a question can have many answers. 一个项目可以有很多问题,一个问题可以有很多答案。 Using PDO's and LEFT JOIN ON the Question ID, how can I turn comments with answers into a multidimensional array so that the structure would look like this: 使用PDO和问题ID上的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
                 )
            )
      )

Finalized Code (which is returning what I want) 最终代码(返回我想要的)

$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']
        ));
      }          
    }

In one query, you can request all answers, join questions to them, and join projects to questions. 在一个查询中,您可以请求所有答案,向他们提出问题,以及向项目提出问题。

  1. Create empty array $projects = array() 创建空数组$projects = array()
  2. Iterate through every resulting row foreach ($rows as $row) 遍历每个结果行foreach ($rows as $row)
  3. Add project with its data to array, if it does not exist already (use project id as key) if (!isset($projects[$row->project_id])) { $projects[$row->project_id] = array('col1' => $row->col1,'questions' => array()); } 将项目及其数据添加到数组(如果尚不存在)(使用项目ID作为键) if (!isset($projects[$row->project_id])) { $projects[$row->project_id] = array('col1' => $row->col1,'questions' => array()); } if (!isset($projects[$row->project_id])) { $projects[$row->project_id] = array('col1' => $row->col1,'questions' => array()); }
  4. Add question with its data to project questions array, if it does not exist already (use question id as key) if (!isset($projects[$row->project_id]['questions'][$row->question_id])) { $projects[$row->project_id]['questions'][$row->question_id] = array('col2' => $row->col2,'answers' => array()); } 将问题及其数据添加到项目问题数组(如果尚不存在)(使用问题ID作为键) if (!isset($projects[$row->project_id]['questions'][$row->question_id])) { $projects[$row->project_id]['questions'][$row->question_id] = array('col2' => $row->col2,'answers' => 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()); }
  5. Add answer with its data to project question answers array (use answer id as key) $projects[$row->project_id]['questions'][$row->question_id]['answers'][$row->answer_id] = array('col3' => $row->col3); 将答案及其数据添加到项目问题答案数组(使用答案ID作为键) $projects[$row->project_id]['questions'][$row->question_id]['answers'][$row->answer_id] = array('col3' => $row->col3);

But as you can understand, you will get many useless information in that query. 但是,您可以理解,该查询将获得许多无用的信息。 You could go with one query, getting projects only, iterate through them, in each cycle add data to array and query again to get questions that has specific project_id, iterate through them, in each cycle add data to array and query again to get answers that has specific question_id, iterate through them, and add data to array. 您可以进行一个查询,仅获取项目,进行遍历,在每个周期中将数据添加到数组中,然后再次查询以获取具有特定project_id的问题,遍历它们,在每个周期中将数据添加到数组中并再次查询以获取答案具有特定的question_id,对其进行迭代,然后将数据添加到数组。

But if I rethink this, I think MySQL will work faster than PHP, even with returning bunch of useless data (I mean, repeating data about projects and questions) and 1 query vs possible 50 queries from one client is much better, so I suggest better use first method. 但是,如果我重新考虑这一点,我认为即使返回一堆无用的数据(我的意思是,重复有关项目和问题的数据),并且从一个客户端进行1个查询(可能有50个查询),MySQL都会比PHP更快地工作,所以我建议最好使用第一种方法。

Without further information about your database table and columns, you wont get from me anything more than pseudo-code-algorithm. 没有关于您的数据库表和列的更多信息,除了伪代码算法之外,您不会从我这里得到任何其他信息。

EDIT: Possible MySQL select query: 编辑:可能的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

For table structure 用于表结构

  • project -> | 项目-> | id | id | title | 标题|
  • question -> | 问题-> | id | id | question | 问题 askedBy | 问| project_id | project_id |
  • answer -> | 答案-> | id | id | answer | 回答| answeredBy | 回答者| question_id | 问题ID |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM