2011-03-29 69 views
1

我不擅长用PHP我会说实话。我有一段时间的代码片段,现在实际上可以工作,但它随机化了文本,而不是一次一行地执行。我需要它在旋转时保持平衡。这是我有:一行一行地循环?

$test = file('my_txt_file.txt'); 
$randomized = $test[ mt_rand(0, count($test) - 1) ]; 

然后我可以在我的页面随时根据需要回显$随机。但就像我说的我的问题是我不想随机,但按顺序逐行,循环无止境。任何想法?

+0

你想要什么时候改变价值?在每一页上加载? – salathe 2011-03-31 12:13:10

回答

0

你可以使用一个for循环:

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 
} 
2

使用迭代器从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 

这种方法让我们您随意访问数组,而无需显式的列表。所以你可以在任何地方写回波线(或一些变化)。根据我对你的问题的理解,应该比for循环更好。

如果你没有SPL,显然你将不得不定义你自己的迭代器类来使用这种方法。

0
<?php 
$test = file('test.txt'); 
for ($i = 0; $i < count($test); $i++) { 
     echo $test[$i]; 
     if ($i == (count($test)-1)) { 
       $i = -1; 
     } 
} 
?> 
+0

不错的重复的答案:-p(im确定你的ddnt是什么意思^ _ ^) – Neal 2011-03-29 17:45:50

+0

@Neal,伟大的思想...... – Jordan 2011-03-29 17:47:09

1

如果你没有SPL,你可以这样做:

$test = file('my_txt_file.txt'); 
$test_counter = 0; 


// Whenever you want to output a line: 
echo $test[$test_counter++ % count($test)]; 

将工作超过2十亿迭代。

+0

好的选择我的答案! – Matt 2011-03-29 17:49:52

+0

@Matt - 除了注释的格式太有限外,还会添加注释到您的答案。 – 2011-03-29 17:58:15