随机播放并显示 .txt 文件的内容
Shuffle and Display the Contents of .txt File
我正在尝试阅读、随机播放然后显示文本文件的内容。文本文件包含代码列表(每个代码换行 - 无逗号等)。
1490
1491
1727
364
466
//...
783
784
786
我的代码:
$file = fopen("keywords.txt", "r");
shuffle($file);
while (!feof($file)) {
echo "new featuredProduct('', ". "'". urlencode(trim(fgets($file))) ."')" . "," . "\n<br />";
}
fclose($file);
我得到的结果如下:
new featuredProduct('', '1490'),
new featuredProduct('', '1491'),
new featuredProduct('', '1727'),
new featuredProduct('', '364'),
new featuredProduct('', '466'),
//...
new featuredProduct('', '783'),
new featuredProduct('', '784'),
new featuredProduct('', '786'),
我认为我必须在循环显示之前将 $file
变量的内容打乱,正如您所见,打乱功能不起作用或者我没有正确使用它?
我期待看到列表的排列更加随机。
这应该适合你:
只需使用 file()
, then just use shuffle()
将您的文件读入数组即可随机排列数组。然后你可以遍历它并显示它,像这样:
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
shuffle($lines);
foreach($lines as $line)
echo "new featuredProduct('', '". urlencode(trim($line)) ."'),\n<br />";
?>
正如我上面所写,shuffle()
是对数组进行洗牌。但是fopen()
returns一个资源。
我认为你的问题是 php 中的 shuffle 函数必须在参数中有一个数组,就像你在这里看到的那样:
http://www.w3schools.com/php/func_array_shuffle.asp
所以你必须首先启动一个数组,将所有值添加到它:http://www.w3schools.com/php/func_array_push.asp
然后洗牌,比如:
<code>$file = fopen("keywords.txt", "r");
$a=array();
while (!feof($file)) {
array_push($a,urlencode(trim(fgets($file))));
}
fclose($file);
shuffle($a);
// And here you display your array shuffled.
希望对您有所帮助。
我正在尝试阅读、随机播放然后显示文本文件的内容。文本文件包含代码列表(每个代码换行 - 无逗号等)。
1490
1491
1727
364
466
//...
783
784
786
我的代码:
$file = fopen("keywords.txt", "r");
shuffle($file);
while (!feof($file)) {
echo "new featuredProduct('', ". "'". urlencode(trim(fgets($file))) ."')" . "," . "\n<br />";
}
fclose($file);
我得到的结果如下:
new featuredProduct('', '1490'),
new featuredProduct('', '1491'),
new featuredProduct('', '1727'),
new featuredProduct('', '364'),
new featuredProduct('', '466'),
//...
new featuredProduct('', '783'),
new featuredProduct('', '784'),
new featuredProduct('', '786'),
我认为我必须在循环显示之前将 $file
变量的内容打乱,正如您所见,打乱功能不起作用或者我没有正确使用它?
我期待看到列表的排列更加随机。
这应该适合你:
只需使用 file()
, then just use shuffle()
将您的文件读入数组即可随机排列数组。然后你可以遍历它并显示它,像这样:
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
shuffle($lines);
foreach($lines as $line)
echo "new featuredProduct('', '". urlencode(trim($line)) ."'),\n<br />";
?>
正如我上面所写,shuffle()
是对数组进行洗牌。但是fopen()
returns一个资源。
我认为你的问题是 php 中的 shuffle 函数必须在参数中有一个数组,就像你在这里看到的那样:
http://www.w3schools.com/php/func_array_shuffle.asp
所以你必须首先启动一个数组,将所有值添加到它:http://www.w3schools.com/php/func_array_push.asp
然后洗牌,比如:
<code>$file = fopen("keywords.txt", "r");
$a=array();
while (!feof($file)) {
array_push($a,urlencode(trim(fgets($file))));
}
fclose($file);
shuffle($a);
// And here you display your array shuffled.
希望对您有所帮助。