加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 20:50:52 所属栏目:PHP教程 来源:网络整理
导读:?php //第一种方法: $line =getrandline1( test.txt ); function getrandline1( $filename ) { $linenum =0; $fh = fopen ( $filename , r ); while (! feof ( $fh )) { if ( $rowcontents = fgets ( $fh )) { $linenum ++; $contens []= $rowcontents ; }
  1. <?php 
  2. //第一种方法: 
  3. $line = getrandline1('test.txt'); 
  4. function getrandline1($filename
  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. $line = getrandline2('test.txt'); 
  22. function getrandline2($filename
  23.  $contents = file('test.txt'); 
  24.  $linenum = count($contents); 
  25.  $randline = mt_rand(0, $linenum - 1); 
  26.  $line = $contents[$randline]; 
  27.  return $line
  28.   
  29. //第三种方法: 
  30. $line = getrandline3('test.txt'); 
  31. function getrandline3($filename
  32.  $contents = file('test.txt'); 
  33.  shuffle($contents); 
  34.  return $contents[0]; 
  35.   
  36. //第四种方法: 
  37. $line = getrandline4('test.txt'); 
  38. function getrandline4($filename
  39.  $linenum = 0; 
  40.  $fh = fopen($filename'r'); 
  41.  while(!feof($fh)) 
  42.  { 
  43.   if($linecontents = fgets($fh)) 
  44.   { 
  45.    $linenum++; 
  46.                         $randint = (mt_rand(1, 1000000 * $linenum) - 1)/1000000); 
  47.    if($randint < 1) 
  48.    { 
  49.     $line = $linecontents
  50.    } 
  51.   } 
  52.  } 
  53.  fclose($fh); 
  54.  return $line
  55. ?> 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读