【问题标题】:How to slice array then shuffle it如何切片数组然后洗牌
【发布时间】:2023-03-07 07:59:01
【问题描述】:

我有一个函数,它可以从一个字符串创建一个单词数组,计算每个单词出现的频率,然后选择前 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>";
}

【问题讨论】:

    标签: php


    【解决方案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>";
    }
    

    【讨论】:

    • 谢谢 Mihai,但我不确定这将如何与我已有的一起工作?
    猜你喜欢
    • 2012-03-10
    • 2013-07-18
    • 1970-01-01
    • 2019-05-08
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    相关资源
    最近更新 更多