我一直在编写一个脚本,该脚本从数据库中提取推荐,将每个结果添加到一个数组中,然后计算每个单词在整个数组中出现的次数。
这工作正常,但我现在需要做的是抓取该数组并循环它以显示数组中出现的前 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/