2013-07-31 122 views
0

我意識到這是非常簡單的,但我覺得我看起來有些東西。 我想屏幕顯示是PHP:循環邏輯


RED This is 0. 

GREEN This is 1. 

,並且它可以來回交替顯示的文本之間。我的邏輯如果罰款交替紅色和綠色,但「這是0」和「這是1」文本不顯示。

這裏是我到目前爲止的代碼:

<?php 

$array = array(0=>"RED",1=>"GREEN"); 
$a_count = 0; 
$count = 0; 


while($count<10) 
// DO 9 TIMES 
{ 

    echo $array[$a_count] . ' '; 
    //SUDO FOR IMAGE BEING DISPLAYED 

    while($array[$a_count] == 0) 
    { 
     echo "This is 0.<br>"; 
    } 

    while($array[$a_count] == 1) 
    { 
     echo "This is 1<br>"; 
    } 


//<----SWITCH BACK AND FORTH----> 
    if($a_count == 1) 
    { 
     $a_count = 0; 
    } 
    else 
    { 
     $a_count++; 
    } 
//<-----------------------------> 
    $count++; 
} 

?> 

我認識的最簡單的辦法是什麼,我想的是:

<?php 

$array = array(0=>"RED",1=>"GREEN"); 
$a_count = 0; 
$count = 0; 


while($count<10) 
// DO 9 TIMES 
{ 

    echo $array[$a_count] . ' '; 
    //SUDO FOR IMAGE BEING DISPLAYED 


//<----SWITCH BACK AND FORTH----> 
    if($a_count == 1) 
    { 
     echo "This is 1<br>"; 
     $a_count = 0; 
    } 
    else 
    { 
     echo "This is 0.<br>"; 
     $a_count++; 
    } 
//<-----------------------------> 
    $count++; 
} 

?> 

但是這個代碼不包含我所需要的邏輯爲這個項目的延續。 我非常感謝答案,爲什麼我的第一個代碼不打印「這是0」。

謝謝!

+0

你在找什麼邏輯?你已經回答了你自己的問題 – 2013-07-31 16:47:40

回答

1

爲什麼不能是這樣的:

$colors = array(0 => 'Red', 1 => 'Green'); 
$idx = 0; 
$count = 0; 
while($count < 10) { 
    echo "The color is {$colors['$idx']}<br />"; 
    $count = 1 - $count; // if $count is 1, it becomes 0. if it's 0, it becomes 1 
} 

你而()循環基本上是完全無用的。你試圖再次將RED和GREEN字符串進行比較0.如果任何評估都是正確的,那麼最終會出現無限循環。

0

您在while循環中沒有更改$a_count的值,所以無法結束它們。

的問題是在這裏:

while($array[$a_count] == 0) 
{ 
    echo "This is 0.<br>"; 
} 

while($array[$a_count] == 1) 
{ 
    echo "This is 1<br>"; 
} 

一旦它進入第一環,它只會保留呼應"This is 0.<br>",作爲$a_count是不變的。

看起來您可以將這些while s更改爲if s,以使您的代碼按照您的要求工作。你也可能想檢查$a_count是0還是1,而不是$array[$a_count]

0

忽略此腳本的低效率,您的while循環將與數組的值進行比較,而不是其鍵。但解決這個問題實際上會暴露另一個 - 無限循環。

+0

我真的很感激它。謝謝。 – beckah

0

那麼,在你的第一個例子之前($ count < 10),你有沒有初始化你的值? 如果你這樣做,你必須有一個這樣的顯示:

RED This is 0.0 
This is 0.0 
This is 0.0 
This is 0.0 
This is 0.0 
... 

「這是0.0」是一個無限循環顯示。

while($array[$a_count] == 0) 
    { 
     echo "This is 0.$count<br>"; 
    } 

    while($array[$a_count] == 1) 
    { 
     echo "This is 1<br>"; 
    } 

您必須在while循環中更改該值。

其他技巧,我想你看看「foreach」php循環。可以用於你想要做的事情。 modulos也可以幫助你。

+0

不幸的是,這不是我得到的 這就是我得到的是:紅色綠色綠色綠色綠色綠色綠色綠色綠色 – beckah

+0

我還初始化了$計數,同時在開始時聲明我的變量。 – beckah

+0

你有嗎? :$ array = array(0 =>「RED」,1 =>「GREEN」); $ a_count = 0; $ count = 0;我複製/粘貼你的第一個代碼,在開始時添加這個代碼。 –

0

我認爲最簡單的方法是使用switch語句。因爲之前沒有想過,我感到非常愚蠢。

while($count<10) 
{ 

    echo $array[$a_count] . ' '; 
    //PSUEDO FOR IMAGE BEING DISPLAYED 

    switch($a_count): 
    { 
     case 1: 
      echo "This is RED.<br>"; 
      $a_count = 0; 
      break; 

     case 0: 
      echo "This is GREEN.<br>"; 
      $a_count++; 
      break; 

    } 

    $count++; 
}