Php 循环遍历数组计数值并显示前10名

Php 循环遍历数组计数值并显示前10名,php,Php,我一直在编写一个脚本,它从数据库中提取推荐信,将每个结果添加到一个数组中,然后计算每个单词在整个数组中出现的次数 这很好,但我现在需要做的是抓取该数组并循环它以显示数组中出现的前10个单词。我不知道最有效的方法是什么 这是我现有的代码 $result = mysql_query("SELECT testimonial FROM testimonials WHERE active = 1") or die(mysql_error()); $testimonials = array(); if(m

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

这很好,但我现在需要做的是抓取该数组并循环它以显示数组中出现的前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)));

如果有任何帮助,我们将不胜感激。

事实上,如果有以下帮助,整个过程会更容易:

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

节省内存,更易于阅读

您的获取有点冗长,您可以更轻松地完成(请参阅我的回复)