php 文件中隨機取出一條數據
來源:程序員人生 發布時間:2014-03-01 09:13:33 閱讀次數:3938次
- <?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;
- }
- ?>
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
------分隔線----------------------------
------分隔線----------------------------