php 文件中随机取出一条数据
来源:程序员人生 发布时间:2014-03-01 09:13:33 阅读次数:3592次
- <?php
-
- $line = getrandline1('test.txt');
- function getrandline1($filename)
- {
- $linenum = 0;
- $fh = fopen($filename, 'r');
- while(!feof($fh))
- {
- if($rowcontents = fgets($fh))
- {
- $linenum++;
- $contens[] = $rowcontents;
- }
- }
- $randline = mt_rand(0, $linenum - 1);
- $line = $contens[$randline];
- fclose($fh);
- return $line;
- }
-
-
- $line = getrandline2('test.txt');
- function getrandline2($filename)
- {
- $contents = file('test.txt');
- $linenum = count($contents);
- $randline = mt_rand(0, $linenum - 1);
- $line = $contents[$randline];
- return $line;
- }
-
-
- $line = getrandline3('test.txt');
- function getrandline3($filename)
- {
- $contents = file('test.txt');
- shuffle($contents);
- return $contents[0];
- }
-
-
- $line = getrandline4('test.txt');
- function getrandline4($filename)
- {
- $linenum = 0;
- $fh = fopen($filename, 'r');
- while(!feof($fh))
- {
- if($linecontents = fgets($fh))
- {
- $linenum++;
- $randint = (mt_rand(1, 1000000 * $linenum) - 1)/1000000);
- if($randint < 1)
- {
- $line = $linecontents;
- }
- }
- }
- fclose($fh);
- return $line;
- }
- ?>
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
------分隔线----------------------------
------分隔线----------------------------