0

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"
);
2
  • 1
    I know it's not very helpful, but if you want to query and update data like that, you may want to have a look at no-sql solutions like MongoDB. You insert and query on objects, and the result is exactly as you have posted. Commented Nov 18, 2012 at 16:47
  • Looks interesting, will definitely try it out! Commented Nov 18, 2012 at 16:51

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.