PHP:str_word_count打印单词和重复单词的数量

时间:2013-06-04 00:12:13

标签: php

我想找到最近50个帖子中的标签,并打印出重复标签的数量?

到目前为止,我打印了标签。如何打印“重复标记的数量”的数量。

$posts = mysql_query("SELECT * FROM posts ORDER BY id desc Limit 50");

while($fetch_tags = mysql_fetch_assoc($posts))
{
    $tags_array  = str_word_count($fetch_tags['tags'],1);
}

foreach($tags_array as $tag)
{
    echo $tag .'<br/>';   // ex: html</br/>php</br/> ...etc.
}

我希望输出像$tag:$number<br/> ...

1 个答案:

答案 0 :(得分:0)

你可以读取数组:

$posts = mysql_query("SELECT * FROM posts ORDER BY id desc Limit 50");
$results = array();

while($fetch_tags = mysql_fetch_assoc($posts))
{
    $tags_array  = str_word_count($fetch_tags['tags'],1);

    foreach($tags_array AS $index => $tag) {
        if ( !isset($results[$tag]) ) $results[$tag] = 1; // First occurrence
        else $results[$tag] += 1; // Add one occurrence
    }
}

// Now that we counted, print the results
foreach($results AS $tag => $number)
{
    echo "{$tag} : {$number}<br />\n";
}