Home > Backend Development > PHP Tutorial > Four ways to randomly extract a piece of data from a php file_PHP tutorial

Four ways to randomly extract a piece of data from a php file_PHP tutorial

WBOY
Release: 2016-07-13 10:43:50
Original
1966 people have browsed it

This article will introduce to you an example of randomly extracting a piece of data from a php file. I hope this tutorial will be helpful to all students.

 代码如下 复制代码
//第一种方法:
$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;
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/633151.htmlTechArticleThis article will introduce to you an example of randomly extracting a piece of data from a php file. I hope this tutorial will be useful to all students. Help. The code is as follows Copy code ?php //First method: $lin...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template