【问题标题】:PHP - how to echo random lines from txt file?PHP - 如何从 txt 文件中回显随机行?
【发布时间】:2018-06-01 05:36:20
【问题描述】:

我想通过 PHP 从文件 sitemap.txt 中回显随机行,提供为:

link1
link2
link3
link4
...
link10000

我尝试过使用这个功能:

$lines = file("sitemap.txt");

$data[link] = $lines[array_rand($lines)];

但是这个$data[link]只会回显输出1个随机值,例如link1或link10000

但是,我需要从 sitemap.txt 回显 100 个随机值

如何优化这个功能?

谢谢

【问题讨论】:

  • 用于每个循环

标签: php arrays random


【解决方案1】:
$lines = file("sitemap.txt");

$data = array_rand($lines, 100);
foreach($data as $value) {
    echo $lines[$value]."<br>";
};

输出最多 100 行。

   link3 
    link4 
    ..
    ..

【讨论】:

    【解决方案2】:

    您可以使用 shuffle 和 array_slice。

    $lines = file("sitemap.txt");
    Shuffle($lines);
    Echo implode("<br>", array_slice($lines, 0, 100));
    

    这将打乱链接并提取 100 个然后在每一行回显它们。
    使用非循环解决方案是解决此类问题的最快方法。

    在此处查看简单示例:https://3v4l.org/Oqnot

    【讨论】:

      【解决方案3】:

      您可以尝试使用 shuffle 函数在数组中混合值。然后在for循环中使用array_pop函数。

      shuffle($lines);
      for ($i = 0; $i < 100; $i++) {
          echo $lines[$i];
      }
      

      【讨论】:

        【解决方案4】:

        你可以试试这个

          $array=array(); // declaration of array 
          $array=explode("\n", file_get_contents('new.txt')); // get the text file
          shuffle($array); // where array shuffles inside the array
        
          // below just to show if array is already shuffles
        
         foreach($array as $a){
           echo $a;
          }
            //end code
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-02-28
          • 1970-01-01
          • 1970-01-01
          • 2020-10-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多