使用mysql或php对带有tags的tag进行分组/格式化
作者:互联网
可以说我们有一个像这样的数组
从像
function getGroups($limit = 10) {
$data = $this->fetchAll ( 'SELECT gid, `group`, information, tag FROM groups
GROUP BY tag LIMIT ' . $limit );
return $data;
}
结果
array
0 =>
array
'gid' => string '6' (length=1)
'group' => string 'Media' (length=5)
'tag' => string 'advertising' (length=11)
1 =>
array
'gid' => string '8' (length=1)
'group' => string 'Fashion' (length=10)
'tag' => string 'shorts' (length=7)
2 =>
array
'gid' => string '7' (length=1)
'group' => string 'Automotive' (length=8)
'tag' => string 'cars' (length=5)
3 =>
array
'gid' => string '1' (length=1)
'group' => string 'Fashion' (length=7)
'tag' => string 'tshirt' (length=6)
我需要对此显示某种方式(类似)
array
0 =>
array
'group' => string 'Media'
'tags'
array
0 => string 'advertising'
1 =>
array
'group' => string 'Fashion'
'tags'
array
0 => string 'short'
1 => string 'tshirt'
2 =>
array
'group' => string 'Automotive'
'tags'
array
0 => 'cars'
更简单
group tag
media advertising
fashion short
fashion tshirt
automotive cars
至
media
advertising
fashion
short
tshirt
automotive
cars
做这个的最好方式是什么?从PHP数组?还是从MySQL?
解决方法:
您是否要获取组列表以及每个组的所有标签? GROUP_CONCAT()是获取标签列表的正确方法,但是您希望按组而不是按标签分组:
function getGroups($limit = 10) {
$data = (array) $this->fetchAll (
'SELECT `group`,
GROUP_CONCAT(DISTINCT `tag` ORDER BY `tag`) AS `tags`
FROM `groups`
GROUP BY `group` LIMIT ' . $limit
);
foreach ($data as $i => $row) {
$data[$i]['tags'] = explode(',', $row['tags']);
}
return $data;
}
标签:arrays,mysql,php,formatting 来源: https://codeday.me/bug/20191208/2090662.html