循环遍历array_count_values并显示前10名

时间:2011-11-29 14:40:02

标签: php

我一直致力于从数据库中提取推荐信的脚本,将每个结果添加到数组中,然后计算每个单词在整个数组中出现的次数。

这很好但我现在要做的就是抓住那个数组并循环显示它,以显示我的数组中出现的前10个单词。我不确定最有效的方法......

这是我现有的代码

$result = mysql_query("SELECT testimonial FROM testimonials WHERE active = 1") or die(mysql_error());

$testimonials = array();
if(mysql_num_rows($result)) {
    while($row = mysql_fetch_array($result)) {
      array_push($testimonials, $row['testimonial']);
    }
};

$rawstring = implode(" ", $testimonials);
$words = (array_count_values(str_word_count($rawstring, 1)));

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:4)

// get the word=>count array
$words = array_count_values(str_word_count($rawstring, 1));

// sort on the value (word count) in descending order
arsort($words);

// get the top frequent words
$top10words = array_slice($words, 0, 10);

答案 1 :(得分:0)

实际上整个事情会更容易:

$testimonials = mysql_fetch_array($result);
$wordcount = sort(array_count_values($testimonials)); 
$topten = array_slice($wordcount);
$i = 1;
foreach($topten as $word => $occurence) { echo $i.'Word:'.$word.'('.$occurence.')';$i++; }

节省内存,更容易阅读!