Php 在一个包含10.000行的文件中随机获取10行的最快方法是什么?
我有一个文件,里面有大约10000行。我希望每次用户访问我的网站时,它都会自动从中随机选取10行。Php 在一个包含10.000行的文件中随机获取10行的最快方法是什么?,php,performance,file,random,line,Php,Performance,File,Random,Line,我有一个文件,里面有大约10000行。我希望每次用户访问我的网站时,它都会自动从中随机选取10行。 我目前使用的代码: $filelog = 'items.txt'; $random_lines = (file_exists($filelog))? file($filelog) : array(); $random_count = count($random_lines); $random_file_html = ''; if ($random_count > 10) { $ran
我目前使用的代码:
$filelog = 'items.txt';
$random_lines = (file_exists($filelog))? file($filelog) : array();
$random_count = count($random_lines);
$random_file_html = '';
if ($random_count > 10)
{
$random_file_html = '<div><ul>';
for ($i = 0; $i < 10; $i++)
{
$random_number = rand(0, $random_count - 1); // Duplicate are accepted
$random_file_html .= '<li>'.$random_lines[$random_number]."</li>\r\n";
}
$random_file_html .= '</ul>
</div>';
}
(我的服务器不支持任何类型的SQL)
也许你有其他最适合我的方法。解决我的问题最好的方法是什么?多谢各位 试试看:
$lines = file('YOUR_TXT_FILE.txt');
$rand = array_rand($lines);
echo $lines[$rand];
对于其中的10个,只需将其放在一个循环中:
$lines = file('YOUR_TXT_FILE.txt');
for ($i = 0; $i < 10; $i++) {
$rand = array_rand($lines);
echo $lines[$rand];
}
$lines=file('YOUR_TXT_file.TXT');
对于($i=0;$i<10;$i++){
$rand=数组\u rand($line);
回音$行[$rand];
}
注意:*上述代码不保证**2不会拾取相同的行。为了保证唯一性,您需要添加额外的while循环和一个包含所有随机生成索引的数组,因此下次它生成它并且它已经存在于数组中时,请生成另一个,直到它不在数组中为止
上述解决方案可能不是最快的,但可能满足您的需要。由于您的服务器不支持任何类型的SQL,是否可以切换到其他服务器?因为我想知道您是如何存储用户数据的?那些也存储在文件中吗?最快的方法显然是而不是根据每个用户的请求从一个文件中随机抽取10行,其中大约有10000行。
因为我们不知道这个“XY问题”的细节,所以无法回答更多的问题。如果可以调整文件的内容,那么只需填充每一行,使它们有一个共同的长度。然后可以使用随机访问访问文件中的行
$lineLength = 50; // this is the assumed length of each line
$total = filesize($filename);
$numLines = $total/$lineLength;
// get ten random numbers
$fp = fopen($filename, "r");
for ($x = 0; $x < 10; $x++){
fseek($fp, (rand(1, $numLines)-1)*$lineLength, SEEK_SET);
echo fgets($fp, 50);
}
fclose($fp);
$lineLength=50;//这是每条线的假定长度
$total=文件大小($filename);
$numLines=$total/$lineLength;
//得到十个随机数
$fp=fopen($filename,“r”);
对于($x=0;$x<10;$x++){
fseek($fp,(兰特(1,$numLines)-1)*$lineLength,SEEK_SET);
echo FGET(fp,50美元);
}
fclose($fp);
这显然是最糟糕的方法。更糟/更好的是,它回答了这个问题。为什么更糟糕的方式是你们想详细说明一下呢?若并没有SQL,你们如何存储用户数据?实际上不需要填充。但不管怎么说,这只是一种恶意的行为。我们应该避免如此大规模的数据挖掘,而不是对其进行优化。@YourCommonSense在不填充记录的情况下,如何获得同样的效果?我同意这个问题是可疑的,但从提问的方式来看,我认为这是一个有效的解决方案。
$lineLength = 50; // this is the assumed length of each line
$total = filesize($filename);
$numLines = $total/$lineLength;
// get ten random numbers
$fp = fopen($filename, "r");
for ($x = 0; $x < 10; $x++){
fseek($fp, (rand(1, $numLines)-1)*$lineLength, SEEK_SET);
echo fgets($fp, 50);
}
fclose($fp);