我有两个表,用户和评论。
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']
);
}
我无法想到获得这种结构的最佳方法
答案 0 :(得分:0)
数组的每个键必须是唯一的,因此您不能在数组中的同一级别拥有多个comment
键。
这可能是您所需要的:
$comment[$row['username']][] = array(
'comment' => $row['comment'],
'rating' => $row['rating'],
);