PHP - how to echo random lines from txt file?

瘦欲@ 提交于 2021-02-04 21:06:55

问题


I want to echo random lines by PHP from file sitemap.txt that provide as:

link1
link2
link3
link4
...
link10000

I have tried using this function:

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

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

But this $data[link] will echo output 1 random value only such as link1 or link10000

However, I need to echo 100 random values from sitemap.txt

How can I optimize this function?

Thanks


回答1:


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

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

output is like upto 100 lines.

   link3 
    link4 
    ..
    ..



回答2:


You can use shuffle and array_slice.

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

This will shuffle the links and extract 100 of then and echo them one on each line.
Using non looping solutions is the fastest method for this type of problem.

See simple example here: https://3v4l.org/Oqnot




回答3:


You could try using shuffle function to mix values inside array. And then use array_pop function in for loop.

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



回答4:


you could try this one

  $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


来源:https://stackoverflow.com/questions/50636685/php-how-to-echo-random-lines-from-txt-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!