这是在一个有10.000行的文件中随机获得10行的最快方法


Which is fastest way to get 10 lines randomly inside a file with 10.000 lines?

我有一个文件,里面有大约10000行。我希望每次用户访问我的网站时,它都会自动从中随机选择10行
当前使用的代码I:

$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>';
}

当我有<1000行,一切都还好。但现在,有了1000行。它使我的网站速度明显减慢
我正在考虑其他方法,比如:

将文件分成50个文件,随机选择,然后在所选文件内随机选择10行
--或--
我知道行(项)总数。随机制作10个数字,然后使用读取文件

$file = new SplFileObject('items.txt');
$file->seek($ranđom_number);
echo $file->current();

(我的服务器不支持任何类型的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);

try:

$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];
}

注意:**以上代码不能保证**2不会拾取相同的行。为了保证唯一性,您需要添加额外的while循环和一个数组,该数组包含所有随机生成的索引,所以下次它生成索引时,如果它已经存在于数组中,请生成另一个索引,直到它不在数组中为止。

上述解决方案可能不是最快的,但可能满足您的需求。由于您的服务器不支持任何类型的SQL,是否可以切换到其他服务器?因为我想知道您是如何存储用户数据的?这些也存储在文件中吗?