Reputation: 5116
Is there a way I could get MySQLi to return a multi-dimensional array?
Let's say I'm selecing blog posts from the database, and each post has multiple tags. With my knowledge, I would do this:
$r = $mysqli->query("SELECT * FROM posts");
while ($post = $r->fetch_assoc()) {
//echo blog posts
$t = $mysqli->query("SELECT * FROM blog_tags INNER JOIN tags ON tags.id = blog_tags.tag_id WHERE post_tags.post_id = ".$post['id']);
while($tag = $t->fetch_assoc()){
//echo tags
}
}
But what I'd prefer is doing it like this:
$r = $mysqli->query("SELECT * FROM posts INNER JOIN post_tags ON posts.id = post_tags.post_id INNER JOIN tags ON tags.id = post_tags.tag_id");
while($post = $r->fetch_assoc()){
//echo post
foreach($post['tags'] as $tag){
//echo tags
}
}
So the return would be:
$posts = array(
"id" => 1,
"title" => "Blog post 1",
"content" => "Lorem ipsum...",
"tags" =>
array(
"tag1",
"tag2",
"tag3"
),
"posted" => "1-1-2010 11:11:11"
);
Upvotes: 0
Views: 476
Reputation: 14681
You need to use GROUP BY
and GROUP_CONCAT
. I'm guessing the tag name field is called name
SELECT posts.*, GROUP_CONCAT(tags.name) as tagnames FROM posts
INNER JOIN post_tags ON posts.id = post_tags.post_id
INNER JOIN tags ON tags.id = post_tags.tag_id
GROUP BY posts.id
Then when you get the results, you can explode(",", $t->tagnames)
to get an array of tags.
Upvotes: 1