Heim  >  Artikel  >  Backend-Entwicklung  >  帖子列表里面怎么查出标签

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

WBOY
WBOYOriginal
2016-06-06 20:46:481085Durchsuche

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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn