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