PHP-如何从txt文件中回送随机行?
我想通过PHP从文件sitemap.txt中回传随机行,该文件提供如下内容:PHP-如何从txt文件中回送随机行?,php,arrays,random,Php,Arrays,Random,我想通过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个随机值 如何优化此功能 感谢您可以
link1
link2
link3
link4
...
link10000
我已尝试使用此功能:
$lines = file("sitemap.txt");
$data[link] = $lines[array_rand($lines)];
但是这个$data[link]将只回显输出1个随机值,例如link1或link10000
但是,我需要回显sitemap.txt中的100个随机值
如何优化此功能
感谢您可以尝试使用shuffle函数在数组中混合值。然后在for循环中使用array_pop函数
shuffle($lines);
for ($i = 0; $i < 100; $i++) {
echo $lines[$i];
}
您可以尝试使用shuffle函数在数组中混合值。然后在for循环中使用array_pop函数
shuffle($lines);
for ($i = 0; $i < 100; $i++) {
echo $lines[$i];
}
你可以试试这个
$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
你可以试试这个
$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
您可以使用洗牌和数组_切片
$lines = file("sitemap.txt");
Shuffle($lines);
Echo implode("<br>", array_slice($lines, 0, 100));
这将洗牌链接并提取100个链接,然后在每一行上回显一个链接。
使用非循环解决方案是解决此类问题的最快方法
请参见此处的简单示例:您可以使用随机播放和数组\u切片
$lines = file("sitemap.txt");
Shuffle($lines);
Echo implode("<br>", array_slice($lines, 0, 100));
这将洗牌链接并提取100个链接,然后在每一行上回显一个链接。
使用非循环解决方案是解决此类问题的最快方法
请参见此处的简单示例:每个循环使用每个循环