从文本文件中获取随机行

4

我希望在用户刷新页面时从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); 

这是什么错误?

更新:如果可以避免循环,并且仅更正此代码。


这个会不会给你一个偏移错误? - DirtyBit
4个回答

6

你代码中的问题在于,你只将文件的第一行放入了一个数组中:

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

这里的意思是:
Array (
    [0] => First line
)

所以,如果你已经打开了 错误报告,你会收到以下通知:

注意:未定义的偏移量

75% 的时间会出现这种情况。
但是为了实现你想要的效果,你可以使用 file() 将文件读取到数组中,并结合 array_rand() 使用,例如:
$lines = file("random.txt");
echo $lines[array_rand($lines)];

1
fgets 只获取一行,而不是整个文件。file() 解决方案是正确的。 - aghidini

0

fgets函数逐行读取,因此您需要类似以下的代码:

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

4次循环,4行代码


0

0

有趣的问题=) 你可以尝试我的解决方案:

$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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接