簡體   English   中英

從文本文件中獲取隨機行

[英]Get random lines from text file

我想在random.txt調用隨機單詞,因為用戶刷新頁面但我只得到$word_array[0]而不是任何其他$ word_array [1..3]。

random.txt

hello
how
are
you

PHP代碼:

myfile = fopen("random.txt", "r") or die("Unable to open file!");
$word_array = array(fgets($myfile));

$word = rand(0,4);
$lines[] = fgets($myfile);
echo $word_array[$word];

fclose ($myfile); 

錯誤是什么?

更新:如果可以避免循環,則僅更正此代碼。

您的代碼中的問題是,您只需將文件的第一行放入數組:

$word_array = array(fgets($myfile));

意味着你在這里擁有的是:

Array (
    [0] => First line
)

因此,如果您打開錯誤報告 ,您會收到通知:

注意:未定義的偏移量

75%的時間。

但要做你想做的事,你可以使用file()將你的文件放到一個與array_rand()結合的數組中,例如

$lines = file("random.txt");
echo $lines[array_rand($lines)];

fgets只能逐行讀取。 所以你需要這樣的東西:

$lines[] = fgets($myfile);
$lines[] = fgets($myfile);
$lines[] = fgets($myfile);
$lines[] = fgets($myfile);
echo $lines[$word];

4行4次

簡短:fgets只讀一行你需要創建一個while語句來讀取所有行。

所以:

$array = explode("\n", file_get_contents('random.txt'));

http://php.net/manual/en/function.fgets.php

將每行txt文件讀取到新的數組元素

Interesing question =)您可以嘗試我的解決方案:

$myfile = fopen("random.txt", "r") or die("Unable to open file!");
$words = fgets($myfile);//gets only first line of a file
$num = str_word_count($words) - 1 ;//count number of words, but array index
//starts from 0, so we need -1
$word_array = explode(' ', $words);//gets all words as array

$word = rand(0,$num);//getting random word number
echo $word_array[$word];

fclose ($myfile); 

如果你需要所有行 - 你必須迭代所有行,例如while循環

while($row = fgets($myfile)){
    //same code
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM