Shuffle and display the contents of the .txt file

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

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

My code is:

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

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

fclose($file);

The result 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 figured that I would need to shuffle the contents of the variable $filebefore going through and displaying, and as you can see, the shuffle function doesn’t work or didn’t I use it correctly?

I expected the list to be ordered in a much more random manner.

+2
source share
2 answers

This should work for you:

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() .

+3

, , shuffle php , : 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.
    

, .

+2

Source: https://habr.com/ru/post/1589439/


All Articles