Home >php教程 >php手册 >php 文件中随机取出一条数据四种方法

php 文件中随机取出一条数据四种方法

WBOY
WBOYOriginal
2016-05-25 16:54:141477browse

本文章来给大家介绍php 文件中随机取出一条数据实例,希望此教程对各位同学会有所帮助哦。

<?php
//第一种方法:
$line = getrandline1(&#39;test.txt&#39;);
function getrandline1($filename) {
    $linenum = 0;
    $fh = fopen($filename, &#39;r&#39;);
    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(&#39;test.txt&#39;);
function getrandline2($filename) {
    $contents = file(&#39;test.txt&#39;);
    $linenum = count($contents);
    $randline = mt_rand(0, $linenum - 1);
    $line = $contents[$randline];
    return $line;
}
//第三种方法:
$line = getrandline3(&#39;test.txt&#39;);
function getrandline3($filename) {
    $contents = file(&#39;test.txt&#39;);
    shuffle($contents);
    return $contents[0];
}
//第四种方法:
$line = getrandline4(&#39;test.txt&#39;);
function getrandline4($filename) {
    $linenum = 0;
    $fh = fopen($filename, &#39;r&#39;);
    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;
}
?>


本文地址:

转载随意,但请附上文章地址:-)

Statement:
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