php - 循环 array_count_values 并显示前 10 个

标签 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)));

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

最佳答案

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

关于php - 循环 array_count_values 并显示前 10 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8312600/

相关文章:

php - 如何更改我的 php 的颜色和字体大小?如果我尝试,它不起作用

php - 从 PHP 脚本运行 PHP 脚本的最佳实践是什么?

javascript - 如何使用 Ajax、jQuery 和 PhP 保存当前 DOM?

php - 加权随机选择

javascript - Ajax base64 字符串无法成功工作

php - 我在我的 ubuntu 上安装了 phpmyadmin 但它不工作

php - 多个左连接,如何在php中输出

php - 如何从 SQL 表计算高分?

php - 在评论中按日期排序

php - 使用 php 清空文件