PHP-如何从txt文件中回显随机行? [英] PHP - how to echo random lines from txt file?

查看:99
本文介绍了PHP-如何从txt文件中回显随机行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

link1
link2
link3
link4
...
link10000

我尝试使用此功能:

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

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

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

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

但是,我需要从 sitemap.txt

如何优化此功能?

谢谢

推荐答案

您可以使用shuffle和array_slice.

You can use shuffle and array_slice.

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

这将洗净链接并提取其中的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.

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

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

这篇关于PHP-如何从txt文件中回显随机行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆