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

WBOY
풀어 주다: 2016-06-06 20:46:48
원래의
1085명이 탐색했습니다.

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 학습자의 빠른 성장을 도와주세요!