【问题标题】:Shuffle and Display the Contents of .txt File随机播放并显示 .txt 文件的内容
【发布时间】:2015-05-20 13:12:34
【问题描述】:

我正在尝试阅读、随机播放,然后显示文本文件的内容。文本文件包含一个代码列表(每个代码都在一个新行 - 没有逗号等)。

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 变量的内容进行洗牌,如您所见,洗牌功能不起作用或者我没有正确使用它?

我期待看到列表排列得更加随机。

【问题讨论】:

  • shuffle() 用于数组而不是文件句柄

标签: php file fopen


【解决方案1】:

这应该适合你:

只需使用file() 将您的文件读入一个数组,然后只需使用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() 返回一个资源。

【讨论】:

  • 是的,file() 返回一个可以洗牌的数组,fopen() 返回一个文件指针,所以洗牌不起作用
  • 谢谢 Rizier123。我知道我在使用 fopen() 时哪里出错了。我真的很感谢你的帮助。再次感谢。
【解决方案2】:

我认为你的问题是 php 中的 shuffle 函数必须在参数中有一个数组,就像你在这里看到的那样: http://www.w3schools.com/php/func_array_shuffle.asp
因此,您必须首先启动一个数组,将所有值添加到其中:http://www.w3schools.com/php/func_array_push.asp
然后随机播放,例如:

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

希望对你有所帮助。

【讨论】:

  • 谢谢。这也很有用,适用于我的 while 循环示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
相关资源
最近更新 更多