简体   繁体   English

当一个表包含许多行时,从多个表中获取数据

[英]Getting data from multiple tables when one table contains many rows

I have two tables, users, and comments. 我有两个表,用户和注释。

Users:
id - name - email

comments:
user_id - comment - rating

I am trying to get all the comments for every user, but then put them into an array of this sort of structure. 我试图获取每个用户的所有评论,然后将它们放入这种结构的数组中。

array(
    'john' => array(
        'comment' => array(
             'text' => "had a great time thanks",
             'rating' => 5,
        )  
        'comment' => array(
             'text' => "awesome",
             'rating' => 5,
        )            
    )
    'amy' => array(
        'comment' => array(
             'text' => "it was ok",
             'rating' => 3,
        )  
        'comment' => array(
             'text' => "awesome",
             'rating' => 3,
        )            
    )
)

Is this possible with one sql statement? 一个sql语句可能吗? Here is my code so far 到目前为止,这是我的代码

//get the comments
$stmt = $con->prepare('SELECT c.comment,
                              c.rating,
                              u.username
                    FROM comments c
                    INNER JOIN users u
                    ON c.customer_id = u.id');

$stmt->execute();
$result = $stmt->get_result();
$comments = array();
while($row = $result->fetch_assoc()){
    $comments[] = array(
        'comment' => $row['comment'],
        'rating' => $row['rating'],
        'username' => $row['username']
    );
}

I cant think of the best way to get this structure 我想不出获得这种结构的最佳方法

Each key of an array must be unique so you cannot have multiple comment keys at the same level in your array. 数组的每个键必须唯一,因此数组中的同一级别不能有多个comment键。

This may be what you need: 这可能是您需要的:

$comment[$row['username']][] = array(
'comment' => $row['comment'],
'rating' => $row['rating'],
);

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

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