I am not good with php I'll be honest. I had a snippet of code from a while back that actually works now but it randomizes the text instead of do开发者_StackOverflow社区ing line by line 1 at a time. I need it to be balanced when rotating. Here is what I have:
$test = file('my_txt_file.txt');
$randomized = $test[ mt_rand(0, count($test) - 1) ];
Then I can echo $randomized as needed throughout my page. But like I said my issue is I DO NOT want it random, but line by line in order, looping endlessly. Any thoughts on this??
Use iterators from SPL: http://us.php.net/manual/en/class.infiniteiterator.php
$test = file('my_txt_file.txt');
// this allows you to loop endlessly (vs. ArrayIterator)
$lineIterator = new InfiniteIterator($test);
// ...
// Later where you want to use the current line
echo $lineIterator->current();
$lineIterator->next(); // prepare for next call
This method let's you arbitrarily access the array without having an explicit list. So you can write the echo line (or some variation) anywhere. Should be better than a for loop from what I understand about your question.
If you don't have SPL, obviously you would have to define your own iterator class to use this method.
If you don't have SPL, you could do this:
$test = file('my_txt_file.txt');
$test_counter = 0;
// Whenever you want to output a line:
echo $test[$test_counter++ % count($test)];
Will work for over 2 billion iterations.
you can use a for loop:
for($i = 0; $i < count($test); $i++){
echo $test[$i]; //display the line
if(($i + 1) >= count($test)) $i = -1; //makes the loop infinite
//if you don't want it to be infinite remove the above line
}
<?php
$test = file('test.txt');
for ($i = 0; $i < count($test); $i++) {
echo $test[$i];
if ($i == (count($test)-1)) {
$i = -1;
}
}
?>
精彩评论