2011-03-29 29 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