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

标签 php mysql

我有两个表、用户和评论。

Users:
id - name - email

comments:
user_id - comment - rating

我试图获取每个用户的所有评论,然后将它们放入这种结构的数组中。

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,
        )            
    )
)

用一条sql语句可以实现这一点吗?这是到目前为止我的代码

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

我想不出获得这种结构的最佳方法

最佳答案

数组的每个键都必须是唯一的,因此数组中的同一级别不能有多个 comment 键。

这可能是您所需要的:

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

关于php - 当一个表包含多行时,从多个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22747150/

相关文章:

php - PHP中如何对数组的索引进行排序

php - MySQL复杂的IF语句

php - Auth 尝试方法在 Laravel/Lumen + JWT + 用户自定义模型中如何工作

javascript - jsp中的动态依赖选择框 HELP pls

php - 如何在 PHP 中插入后从 MYSQL 表中检索 ID

php - 编写 PHP API 和 Android 应用程序

mysql - 无法将两个查询合并为一个

PHP - 在 mysqli 查询中使用数组

mysql - 是否可以在 MySQL 中创建具有 UNIX_TIMESTAMP 默认值的列?

php - Redis CLI 未通过 Laravel 显示最近存储的 key