0

有没有办法让 MySQLi 返回一个多维数组?

假设我从数据库中选择博客文章,每篇文章都有多个标签。据我所知,我会这样做:

$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
    }
}

但我更喜欢这样做:

$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
    }
}

所以回报是:

$posts = array(
    "id" => 1,
    "title" => "Blog post 1",
    "content" => "Lorem ipsum...",
    "tags" => 
        array(
            "tag1", 
            "tag2", 
            "tag3"
        ),
    "posted" => "1-1-2010 11:11:11"
);
4

1 回答 1

1

您需要使用GROUP BYGROUP_CONCAT。我猜标签名称字段被称为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

然后当你得到结果时,你可以explode(",", $t->tagnames)得到一个标签数组。

于 2012-11-18T16:51:00.690 回答