php - 统计标签的频率

标签 php mysql

如何获取以下数组中包含的字段中的项目的频率?

//
...
...
//database stuff
while($row=mysql_fetch_array($result))
    { 

        //Retrieve tags for this article
    $tags=$row["art_tags"];

     $tagarray=explode(",",$tags);

    foreach($tagarray as $key  => $value)
        {

//这里需要解决方案
//如何在数据库中搜索整个art_tags字段并获取所有标签的频率

echo $value; 

例如。
//米饭 x 23 次
// bean x 12 次

}

最佳答案

要统计数据库中的所有标签,请使用 array_count_values():

$all_tags = array();
while ($row = mysql_fetch_assoc($result)) {
    $all_tags = array_merge($all_tags, explode(',', $row['art_tags']));
}
$all_tags = array_count_values($all_tags);
echo $all_tags['rice'];

或者,对于一个单一标签,让数据库使用 COUNT(*) 为您完成工作:

$tag = 'rice';
$sql = "SELECT COUNT(*) FROM articles
        WHERE art_tags LIKE '$tag'
        || art_tags LIKE '$tag,%'
        || art_tags LIKE '%,$tag'
        || art_tags LIKE '%,$tag,%'";
$result = mysql_query($sql);
list($number) = mysql_fetch_row($result);

关于php - 统计标签的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6017564/

相关文章:

php - WP 管理员 : Include custom post type archive in link search results

php - 为 phpcs 修改 PEAR 标准

mysql - 无法检索 MYSQL 中使用了 Password() 的行

php - 所选数据库中的表和所选表中的字段

php artisan Schedule :run, 没有计划的命令准备好运行,不知道为什么?

php - 显示来自两个表的信息 php?

php - 将数组中键的数据类型从数字更改为字符串

mysql - 仅当 mysql 中提供了特定相关值时才选择记录

mysql - 返回 future 的营业时间

mysql - 在子表中插入新行后查询父表中的自动递增id