【问题标题】:Insert into array random words on random positions在随机位置插入数组随机单词
【发布时间】:2014-08-24 11:00:16
【问题描述】:

有什么理由使用preg_split("/\s/", $str);在随机位置插入另一个数组,该数组由大文本(1000k+字(1行没有\n\r))组成,另一个数组包含特定的键单词和值多少次?

我需要在文本单词和需要插入的单词之间声明一个单词间距。

一个例子来理解我一直在说什么: 这是添加前的文字:

Array
(
    [0] => Lorem
    [1] => ipsum
    [2] => dolor
    [3] => sit
    [4] => amet,
    [5] => consectetur
    [6] => adipisicing
    [7] => elit,
    [8] => sed
    [9] => do
    [10] => eiusmod
    [11] => temporincididunt
    [12] => ut
    [13] => labore
    [14] => et
 )

这句话是:

Array
(
    [word1] => 2 // like i sayed word1 is the word that needs inserted and 2 is how many times
    [word2] => 3 // like i sayed word2 is the word that needs inserted and 3 is how many times
)

这是添加后的文字:

Array
(
    [0] => Lorem
    [1] => word2
    [2] => ipsum
    [3] => dolor
    [4] => sit
    [5] => word1
    [6] => amet,
    [7] => consectetur
    [8] => adipisicing
    [9] => elit,
    [10] => word1
    [11] => sed
    [12] => do
    [13] => eiusmod
    [14] => word2
    [15] => temporincididunt
    [16] => ut
    [17] => labore
    [18] => word2
    [19] => et
 )

【问题讨论】:

  • array_splice() 位置随机,长度为 0

标签: php arrays random


【解决方案1】:
foreach ($newWords as $newWord => $count) {
    for ($i = 1; $i <= $count; $i++) {
        array_splice($allWords, mt_rand(0, count($allWords)-1), 0, $newWord);
    }
}

【讨论】:

    【解决方案2】:

    如果我正确理解您的需求, 拆分文本后可以使用array_count_values:

    $splitResult = array("Lorem","word2","ipsum","dolor","sit","word1","amet","word1");
    
    $newArray = array_count_values($splitResult);
    

    现在,数组键是单词,数组值是文本中的单词数:

    foreach ($newArray as $key => $value) {
            echo "$key - <strong>$value</strong> <br />"; 
    }
    

    希望对你有帮助

    【讨论】:

    • 好的,这是一个好主意,但我还有另一个问题,我如何检测要插入谁多次以及我忘记输入什么来预先声明关键字(word1,word2)之间的字间距。我会更新问题。
    【解决方案3】:

    简单使用array_count_values

    http://php.net/manual/de/function.array-count-values.php

    $array = array("foo","bar","foo","baz","foo","baz");
    $counts = array_count_values($array);
    
    print_r($counts);
    Array
    (
        [foo] => 3
        [bar] => 1
        [baz] => 2
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2019-09-08
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      相关资源
      最近更新 更多