如何获取以下数组中包含的字段中的项目的频率?
//
...
...
//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 次p>
}
最佳答案
要统计数据库中的所有标签,请使用 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/