开发者

Count Frequency of Tags

How can I get the frequency of an item in a field contained in the following array?

//
...
...
//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)
        {

//need solution here

//how to Search entire art_tags field in the database and get frequency of all tags

echo $value; 

Eg.

// Rice x 23 times

//开发者_如何学Go Beans x 12 times

}


To count up all the tags in your database use 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'];

Or, for one just tag, let the database do the work for you with 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);


One way that you could do this is to use the sql count function. Then you wouldn't need to do this programatically. Though, if you have no control over the query and have to do this in code, you would either have to iterate through the array and check to see if the tag that you are looking for is contained inside each record. Unless the query is already finding only those instances of the tags that you need then just get the size of the array.


you can try this code:

foreach($tagarray as $key  => $value
{  
  $tag_count[$value] += 1;
}

and then:

foreach ($tag_count as $tag => $count)
{
 echo $tag.'x'.$count.'times';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜