douba9020 2012-08-15 16:50
浏览 34
已采纳

如何切片然后将其洗牌

I have an function that creates an array of words from a string, counts how often each word occurs and then selects the top 21 words.

Trouble I'm having is I then need to shuffle those 21 words. If I try shuffle() my foreach loop will output the number of occurences rather than the word itself.

Can someone show me how to do this? Here is my existing function:

$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条回答 默认 最新

  • douqie3391 2012-08-15 16:55
    关注

    you could use

    function shuffle_assoc( $array ) { 
        $keys = array_keys( $array ); 
        shuffle( $keys ); 
        return array_merge( array_flip( $keys ) , $array ); 
    }
    

    eg:

    $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>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀