2012-08-15 97 views
1

我有一个函数可以从字符串中创建一个单词数组,计算每个单词出现的频率,然后选择前21个单词。如何切片数组然后洗牌

我遇到的麻烦是我需要洗牌这21个单词。如果我尝试洗牌()我的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>"; 
} 

回答

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>"; 
} 
+0

感谢米哈伊但我真的不知道如何做到这一点有什么我已经有工作吗? – 2012-08-15 16:59:25

+0

我已编辑我的帖子 – 2012-08-15 17:01:39