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条)

报告相同问题?