PHP显示最流行的标签

2by*_*2by 3 php mysql tags function

我有这样一个数据库:

+----+---------------------+
| id | tags                |
+----+---------------------+
| 1  | test1, test2, test3 |
| 2  | test1, test2, test3 |
| 3  | test1, test2, test3 |
| 4  | test1, test2, test3 |
| 5  | buh1, buh2, buh3    |
+----+---------------------+
Run Code Online (Sandbox Code Playgroud)

现在我想显示此数据库中最受欢迎的标签.我有一个函数,它适用于这样的数组:

$ tag_array = array('test1,test2 test,test3','test2,test4,test2','buh,buh2,buh3');

功能:

function popularTags($tag_array) {
    $p = array();
    foreach($tag_array as $tags) {
        $tags_arr = array_map('trim', explode(',', $tags));
        foreach($tags_arr as $tag) {
            $p[$tag] = array_key_exists($tag, $p) ? $p[$tag]+1 : 1;
        }
    }
    arsort($p);
    return $p;
}
Run Code Online (Sandbox Code Playgroud)

这是显示最流行的标签的方法:

foreach(popularTags($tag_array) as $tag=>$num)
{
    echo $tag, " (", $num, ")<br />";
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是正常的数组.

现在,我想从数据库中获取标签,所以我从数据库中提取值并运行如下函数:

$result = mysql_query("select * from DB ORDER BY date DESC");

while($row = mysql_fetch_array($result)){

   $tag_array = $row["$tags"];

foreach(popularTags($tag_array) as $tag=>$num)
{
    echo $tag, " (", $num, ")<br />";
}

}
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误:

警告:为foreach()提供的参数无效

所以我的问题是如何使用此功能显示数据库中最受欢迎的标签?

谢谢

Red*_*ter 8

我的建议是你规范化你的数据库.然后像这样的查询变得微不足道,并且表现要好得多.

select TagID, count(*)
from EntityTag
group by TagID
order by count(*) descending
limit 5
Run Code Online (Sandbox Code Playgroud)