php专区

 首页 > php专区 > PHP应用 > php函数大全 > php 文件中随机取出一条数据 - php函数

php 文件中随机取出一条数据 - php函数

分享到:
【字体:
导读:
          ?php 第一种方法:$line=getrandline1( 39;test txt 39;);functiongetrandline1($filename){$linenum=0;$fh=fopen($filename, 39;r 3...

php 文件中随机取出一条数据

  1. //第一种方法: 
  2. $line = getrandline1('test.txt'); 
  3. function getrandline1($filename
  4.  $linenum = 0; 
  5.  $fh = fopen($filename'r'); 
  6.  while(!feof($fh)) 
  7.  { 
  8.   if($rowcontents = fgets($fh)) 
  9.   { 
  10.    $linenum++; 
  11.    $contens[] = $rowcontents
  12.   } 
  13.  } 
  14.  $randline = mt_rand(0, $linenum - 1); 
  15.  $line = $contens[$randline]; 
  16.  fclose($fh); 
  17.  return $line
  18.   
  19. //第二种方法: 
  20. $line = getrandline2('test.txt'); 
  21. function getrandline2($filename
  22.  $contents = file('test.txt'); 
  23.  $linenum = count($contents); 
  24.  $randline = mt_rand(0, $linenum - 1); 
  25.  $line = $contents[$randline]; 
  26.  return $line
  27.   
  28. //第三种方法: 
  29. $line = getrandline3('test.txt'); 
  30. function getrandline3($filename
  31.  $contents = file('test.txt'); 
  32.  shuffle($contents); 
  33.  return $contents[0]; 
  34.   
  35. //第四种方法: 
  36. $line = getrandline4('test.txt'); 
  37. function getrandline4($filename
  38.  $linenum = 0; 
  39.  $fh = fopen($filename'r'); 
  40.  while(!feof($fh)) 
  41.  { 
  42.   if($linecontents = fgets($fh)) 
  43.   { 
  44.    $linenum++; 
  45.                         $randint = (mt_rand(1, 1000000 * $linenum) - 1)/1000000); 
  46.    if($randint < 1) 
  47.    { 
  48.     $line = $linecontents
  49.    } 
  50.   } 
  51.  } 
  52.  fclose($fh); 
  53.  return $line
  54. ?> 
分享到:
php 生成N个不重复的随机数实例详解 - ph...
php 生成N个不重复的随机数实例详解 生成随机数时用了mt_rand() 函数,这个函数生成随机数的平均速度要比 rand() 快四倍。  去除数组中的重复值时用了“翻翻法”,就是用 array_flip() 把数组的 key 和 value 交换两次,这种做法比用 array_unique() 快得多。  返回数组前,先使用 shuffle(...
PHP字符截取函数,兼容各类gbk,utf-8编码 ...
PHP字符截取函数,兼容各类gbk,utf-8编码 在PHP中字符截取函数substr只能截取全英文才不会出现乱码如果里面有中文肯定是无法截取的,下面小编来给大家介绍两个兼容各类gbk,utf-8编码字符串截取函数,实例代码如下: function CsubStrPro($str, $start, $length, $charset = "utf-8",...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……