我有一个函数可以从字符串创建一个单词数组,计算每个单词出现的频率,然后选择前21个单词。
我遇到的麻烦是我需要洗掉那21个字。如果我尝试shuffle(),我的foreach循环将输出出现次数而不是单词本身。
有人可以告诉我该怎么做吗?这是我现有的功能:
$rawstring = implode(" ", $testimonials);
$rawstring = filterBadWords($rawstring);
// 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, 21);
shuffle($top10words);
foreach($top10words as $word => $value) {
$class = getClass($value);
echo "<a href=\"#\" id=\"" . $word . "\" class=\"" . $class . "\">" . $word . "</a>";
}
答案 0 :(得分:1)
你可以使用
function shuffle_assoc( $array ) {
$keys = array_keys( $array );
shuffle( $keys );
return array_merge( array_flip( $keys ) , $array );
}
例如:
$top10words = array_slice($words, 0, 21);
$top10words = shuffle_assoc($top10words);
foreach($top10words as $word => $value) {
$class = getClass($value);
echo "<a href=\"#\" id=\"" . $word . "\" class=\"" . $class . "\">" . $word . "</a>";
}