Get file contents into array and shuffle them. Don't output more than once.
I have a text file with a list of sentences on each line. Currently, I just randomize the lines but have many duplicates show up. How can I get these lines into an array and then show them all randomly but don't show a sentence again until all sentences have been shown. Basically, I need to loop through the array one full time before I show the quotes over again.
<?php
$list = file开发者_开发问答('list.txt');
shuffle($list);
echo $list[0];
?>
Shuffle doesn't create duplicates in your array, so this code just works fine:
<?php
$list = array(1,2,3,4,5,6);
shuffle($list);
print_r($list);
?>
Array
(
[0] => 2
[1] => 3
[2] => 6
[3] => 4
[4] => 1
[5] => 5
)
That means you have duplicate lines in your file. If you want to get an array with unique values use this: $unique = array_unique($list);
<?php
$list = array(1,1,2,2,3,3);
$unique = array_unique($list);
shuffle($unique);
print_r($unique);
?>
Array
(
[0] => 3
[1] => 2
[2] => 1
)
One easy way to do this would be instead of shuffling the array every time, just pick a random index. Then, store this index in a list. By that, you can check upon the next function call if you have used this index already (if you store them in a sorted list, you can check that very fast, e.g. by using binary search). If the number of indexes equals the number of lines in your file, you can safely discard your list and start a new one, as all indexes have been used at that point of time.
You can first remove duplicate lines and put the result into an array x.
Then pick one random element from array x, print it, and move it to a second (initially empty) array y. Repeat until array x is empty. Then you can start all over again moving elements from array y to array x.
精彩评论