<?php
$arr=file("1.txt");//请使用准确的文件名代替txt
$n=count($arr)-1;
for ($i=1;$i<=10;$i++){//100的需要显示的行数的例子,不是100时请换为具体数
$x=rand(0,$n);
echo $arr[$x],"\n","<br />";//随机显示一行
}
?>
这个是调用一个txt,怎么改成多个txt或者文件下面的所有txt内容随机
核心是俩函数:glob和shuffle
glob是扫目录下符合要求的文件,shuffle是打乱数组。
demo见下,写了注释,应该能看懂
<?php
$dir = "txt_files/"; // 指定 txt 文件所在文件夹路径
$files = glob($dir . "*.txt"); // 获取文件夹下所有 txt 文件的路径
$lines = array(); // 存储所有 txt 文件中的行数据
foreach ($files as $file) {
$content = file($file); // 读取 txt 文件中的所有行
$lines = array_merge($lines, $content); // 将该文件中的行合并到 $lines 数组中
}
shuffle($lines); // 将 $lines 数组中的元素随机排序
$selectedLines = array_slice($lines, 0, 10); // 选取随机的 10 行数据
foreach ($selectedLines as $line) {
echo $line, "<br>"; // 输出每行数据
}
?>