duanfei1987 2011-11-29 14:40
浏览 134
已采纳

循环遍历array_count_values并显示前10名

I have been working on a script that pulls testimonials from a database, adds each result to an array and then counts the number of times each word occurs in the entire array.

This works fine but what I need to do now is grab that array and loop though it to display the top 10 words that occur in my array. I'm not sure of the most efficient way to do this...

Here is my existing code

$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)));

Any help would be appreciated.

  • 写回答

2条回答 默认 最新

  • duanchao5258 2011-11-29 14:45
    关注
    // 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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?