2013-07-17 47 views
0

如何做一個蛇循環在PHP或如何以後每次扭轉PHP數組它循環 我不知道這是什麼方法或技術被稱爲所以我只是將其稱爲蛇循環。如何扭轉以後每次PHP數組它循環

基本上我想要做的是循環一個數組,然後在下一次循環時顛倒該數組的順序。

我想出了什麼似乎是一個稍顯簡單這樣做的方法,但我不知道這是否是正確的技術或是否有這樣做的更好的方法。

<?php 
$rounds = 4; 
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4') ; 

for($round = 1; $round <= $rounds; $round++){ 
    echo "<h1>Round $round</h1>"; 

    if ($round % 2 == 0) { 
     krsort($teams); 
    }else{ 
     asort($teams); 
    }   

    foreach($teams as $team){ 
     echo "$team<br />"; 
    } 
} 

?> 

輸出:

Round 1 
Team 1 
Team 2 
Team 3 
Team 4 

Round 2 
Team 4 
Team 3 
Team 2 
Team 1 

Round 3 
Team 1 
Team 2 
Team 3 
Team 4 

Round 4 
Team 4 
Team 3 
Team 2 
Team 1 

基本上你可以看到,數組排序ascending如果$round是奇數和descending如果它是一個偶數。

+4

'$隊= array_reverse($隊);' – Orangepill

+0

是的,我試過了更早,它似乎沒有工作。我認爲我把它放在循環的錯誤端口內,因爲現在似乎正在工作。 – bigmike7801

回答

2

使用php的array_reverse函數。

<?php 
$rounds = 4; 
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4') ; 

for($round = 1; $round <= $rounds; $round++){ 
    echo "<h1>Round $round</h1>"; 
    echo implode("<br/>", $teams); 
    $teams = array_reverse($teams); 
} 

?> 
1

我想倒車陣列是昂貴的,我認爲更好的將是計算的倒排索引:

array A (6 length) 0,1,2,3,4,5 

array B (5 length) 0,1,2,3,4 

(len-1)-i 
//^ this should calculate the inverted index, examples: 

//in the array A, if you are index 3: (6-1)-3 = 2, so 3 turns to 2 
//in the array A, if you are index 1: (6-1)-1 = 4, so 1 turns to 4 
//in the array B, if you are index 3: (5-1)-3 = 1, so 3 turns to 1 
//in the array B, if you are index 1: (5-1)-1 = 3, so 1 turns to 3 

我不寫PHP,但它應該是這樣的:

teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4'); 
len = teams.length; 
myindex; //initializing the var 

for(i=0; i<len; i++){ 
    echo "<h1>Round "+ (i+1) +"</h1>"; 
    myindex = i; 

    if(i%2 == 0) { 
     myindex = ((len-1) - i); 
    } 

    echo team[myindex]; 
} 
+0

交替奇數/偶數與「array_reverse」有什麼不同? – bigmike7801

+0

@ bigmike7801我更新了我的答案,您仍然需要交替奇數/偶數,只需在一箇中使用正常索引,並在另一箇中反轉它(計算位置遠遠好於以相反順序重新創建任何數組) – ajax333221

+0

好的,我明白你在說什麼。在任何時候基本上只有2個版本的數組,而不是每次都顛倒過來。 – bigmike7801

0

array_reverse是返回數組的反轉的函數。

如果你想有PHP數組對象已經扭轉在每個週期的內容,那麼你就需要每次都設定數組變量;否則,您可以簡單地在每個循環中返回array_reverse的輸出。

1

修改代碼來實現array_reverse:

<?php 
$rounds = 4; 
$teams = array('Team 1', 'Team 2', 'Team 3', 'Team 4') ; 

for($round = 1; $round <= $rounds; $round++){ 
    echo "<h1>Round $round</h1>"; 

    if ($round % 2 == 0) { 
    $teams = array_reverse($teams); 
    }  
    foreach($teams as $team){ 
    echo "$team<br />"; 
    } 
} 
?>