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. { 
  5.  $linenum = 0; 
  6.  $fh = fopen($filename, 'r'); 
  7.  while(!feof($fh)) 
  8.  { 
  9.   if($rowcontents = fgets($fh)) 
  10.   { 
  11.    $linenum++; 
  12.    $contens[] = $rowcontents; 
  13.   } 
  14.  } 
  15.  $randline = mt_rand(0, $linenum - 1); 
  16.  $line = $contens[$randline]; 
  17.  fclose($fh); 
  18.  return $line; 
  19. } 
  20.   
  21. //第二种方法: 
  22. $line = getrandline2('test.txt'); 
  23. function getrandline2($filename) 
  24. { 
  25.  $contents = file('test.txt'); 
  26.  $linenum = count($contents); 
  27.  $randline = mt_rand(0, $linenum - 1); 
  28.  $line = $contents[$randline]; 
  29.  return $line; 
  30. } 
  31.   
  32. //第三种方法: 
  33. $line = getrandline3('test.txt'); 
  34. function getrandline3($filename) 
  35. { 
  36.  $contents = file('test.txt'); 
  37.  shuffle($contents); 
  38.  return $contents[0]; 
  39. } 
  40.   
  41. //第四种方法: 
  42. $line = getrandline4('test.txt'); 
  43. function getrandline4($filename) 
  44. { 
  45.  $linenum = 0; 
  46.  $fh = fopen($filename, 'r'); 
  47.  while(!feof($fh)) 
  48.  { 
  49.   if($linecontents = fgets($fh)) 
  50.   { 
  51.    $linenum++; 
  52.                         $randint = (mt_rand(1, 1000000 * $linenum) - 1)/1000000); 
  53.    if($randint < 1) 
  54.    { 
  55.     $line = $linecontents; 
  56.    } 
  57.   } 
  58.  } 
  59.  fclose($fh); 
  60.  return $line; 
  61. } 
  62. ?> 
分享到:
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技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……