随机播放并显示.txt文件的内容 [英] Shuffle and Display the Contents of .txt File

查看:114
本文介绍了随机播放并显示.txt文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图阅读,洗牌,然后显示文本文件的内容。该文本文件包含一个代码列表(每一个新行 - 没有逗号等)。

  1490 
1491
1727
364
466
// ...
783
784
786

我的代码:

  $ file = fopen (keywords.txt,r); 
shuffle($ file);
$ b $ while(!feof($ file)){
echonew featuredProduct('',。'。urlencode(trim(fgets($ file))) )。 ,。 \\\
< 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() ,然后使用 shuffle() 来洗牌数组。然后你可以遍历它并显示它,如下所示:

 <?php 

$ lines = file(test.txt,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
shuffle($ lines);
$ b foreach($ lines as $ line)
echonew featuredProduct('','。urlencode(trim($ line))。'),\\\
< br / >中;

?>

正如我上面所写, shuffle()是要洗一个数组。但是 fopen()会返回一个资源。


I am trying to read, shuffle, then display the contents of a text file. The text file contains a list of codes (each one on a new line - no commas etc).

1490
1491
1727
364
466
//...
783
784
786

My code:

$file = fopen("keywords.txt", "r");
shuffle($file);

while (!feof($file)) {
  echo "new featuredProduct('', ". "'". urlencode(trim(fgets($file))) ."')" . "," . "\n<br />";
}

fclose($file);

The result I get is the following:

new featuredProduct('', '1490'), 
new featuredProduct('', '1491'), 
new featuredProduct('', '1727'), 
new featuredProduct('', '364'), 
new featuredProduct('', '466'), 
//... 
new featuredProduct('', '783'), 
new featuredProduct('', '784'), 
new featuredProduct('', '786'), 

I believed that I would have to shuffle the contents of the $file variable before looping through and displaying, and as you can see, the shuffle function is not working or I have not used it correctly?

I was expecting to see the list arranged a lot more randomly.

解决方案

This should work for you:

Just read your file into an array with file(), then just use shuffle() to shuffle the array. And then you can loop over it and display it, like this:

<?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 />";

?>

And as I wrote above, shuffle() is to shuffle an array. But fopen() returns a resource.

这篇关于随机播放并显示.txt文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆