貼文清單裡面怎麼查出標籤

來源:互聯網
上載者:User
list和tag都是資料庫裡的資料,想要用mysql這樣的查詢語句查詢出來,得到下面的查詢結果,在不用foreach這樣的php迴圈語句下得到結果

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'), );

這樣的,該怎樣查出

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')    ),),)

這樣的資料?

PS:就像本站的列表是怎麼顯示的標籤的?

回複內容:

list和tag都是資料庫裡的資料,想要用mysql這樣的查詢語句查詢出來,得到下面的查詢結果,在不用foreach這樣的php迴圈語句下得到結果

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'), );

這樣的,該怎樣查出

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')    ),),)

這樣的資料?

PS:就像本站的列表是怎麼顯示的標籤的?

SELECT posts.id AS post_id, posts.title AS post_title, GROUP_CONCAT(tags.name AS tag_name)FROM posts, tag_posts, tagsWHERE tag_posts.post_id = posts.idAND tag_posts.tag_id = tags.id GROUP BY post_title

額,突然明白過來你可能是在問MySQL的查詢語句..好囧,好像這個需求能用JOIN搞定?SELECT * FROM `list` LEFT JOIN `tag` ON list.id = tag.list_id,這個試試?

$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); 
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.