问题
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