我有两个表、用户和评论。
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/