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? 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.
This may be what you need:
$comment[$row['username']][] = array(
'comment' => $row['comment'],
'rating' => $row['rating'],
);