帖子列表里面怎么查出标签

WBOY
发布: 2016-06-06 20:46:48
原创
1084 人浏览过

list和tag都是数据库里的数据,想要用mysql这样的查询语句查询出来,得到下面的查询结果,在不用foreach这样的php循环语句下得到结果

<code>list => array(
    array(id => 1, title => '这是title'),
    array(id => 2, title => '这是title2'),
)//list_id和list里的id关联
tag => array(
    array(id => 1, list_id = 1, name => 'tag1'), 
    array(id => 2, list_id = 1, name => 'tag2'), 
    array(id => 3, list_id = 2, name => 'tag3'), 
);
</code>
登录后复制
登录后复制

这样的,该怎样查出

<code>select => array(
array(
    id => 1, 
    title => '这是title',
    tag =>array(
       array( id =1, name => 'tag1'),
        array(id=2,name='tag2')
    ),
),
array(
    id => 2, 
    title => '这是title2'
    tag =>array(
        array( id =3, name => 'tag3')
    ),
),
)
</code>
登录后复制
登录后复制

这样的数据?

PS:就像本站的列表是怎么显示的标签的?

回复内容:

list和tag都是数据库里的数据,想要用mysql这样的查询语句查询出来,得到下面的查询结果,在不用foreach这样的php循环语句下得到结果

<code>list => array(
    array(id => 1, title => '这是title'),
    array(id => 2, title => '这是title2'),
)//list_id和list里的id关联
tag => array(
    array(id => 1, list_id = 1, name => 'tag1'), 
    array(id => 2, list_id = 1, name => 'tag2'), 
    array(id => 3, list_id = 2, name => 'tag3'), 
);
</code>
登录后复制
登录后复制

这样的,该怎样查出

<code>select => array(
array(
    id => 1, 
    title => '这是title',
    tag =>array(
       array( id =1, name => 'tag1'),
        array(id=2,name='tag2')
    ),
),
array(
    id => 2, 
    title => '这是title2'
    tag =>array(
        array( id =3, name => 'tag3')
    ),
),
)
</code>
登录后复制
登录后复制

这样的数据?

PS:就像本站的列表是怎么显示的标签的?

<code class="lang-sql">SELECT posts.id AS post_id, posts.title AS post_title, GROUP_CONCAT(tags.name AS tag_name)
FROM posts, tag_posts, tags
WHERE tag_posts.post_id = posts.id
AND tag_posts.tag_id = tags.id 
GROUP BY post_title
</code>
登录后复制

额,突然明白过来你可能是在问MySQL的查询语句..好囧,好像这个需求能用JOIN搞定?SELECT * FROM `list` LEFT JOIN `tag` ON list.id = tag.list_id,这个试试?

<code>$lists = array();
foreach($list as $item) 
    $lists[ $item['id'] ] = array('id'=>$item['id], 'title'=>$item['title']);

foreach($tag as $item) {
    $lists[ $item['list_id'] ]['tag'][] = array('id'=>$item['id'], 'name'=>$item['name']);

/*为了得到你的问题中的效果,其实这步有点多余。*/
$lists = array_values($lists); 
</code>
登录后复制
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!