2011-11-29 54 views
2

我一直在努力的脚本,从数据库拉褒奖,将每个结果添加到一个数组,然后计算每个单词出现在整个数组中的次数。循环array_count_values和显示前10

这工作正常,但我现在要做的是抓住该数组并循环,虽然它显示我的数组中出现的前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))); 

任何帮助,将不胜感激。

+0

您的抓取有点冗长,您可以更轻松地做到这一点(请参阅我的回复) – Anonymous

回答

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); 
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++; } 

节省内存,是比较容易的方式来阅读!