2010-10-03 102 views
1
$teams = array(1, 2, 3, 4, 5, 6, 7, 8); 
$game1 = array(2, 4, 6, 8); 
$game2 = array(); 

如果teams[x]game1然後插入game2幫助For循環。值重複

for($i = 0; $i < count($teams); $i++){ 
    for($j = 0; $j < count($game1); $j++){ 
     if($teams[$i] == $game1[$j]){ 
      break; 
     } else { 
      array_push($game2, $teams[$i]); 
     } 
    } 
} 

for ($i = 0; $i < count($game2); $i++) { 
    echo $game2[$i]; 
    echo ", "; 
} 

林希望得到的結果是:

1, 3, 5, 7, 

然而,即時得到:

1, 1, 1, 1, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 

我怎樣才能改善這一點?謝謝

回答

5

其他人已經回答如何使用array_diff

之所以現有的循環不起作用:

if($teams[$i] == $game1[$j]){ 
     // this is correct, if item is found..you don't add. 
     break; 
    } else { 
     // this is incorrect!! we cannot say at this point that its not present. 
     // even if it's not present you need to add it just once. But now you are 
     // adding once for every test. 
     array_push($game2, $teams[$i]); 
    } 

您可以使用一個標誌,修復現有的代碼爲:

for($i = 0; $i < count($teams); $i++){ 
    $found = false; // assume its not present. 
    for($j = 0; $j < count($game1); $j++){ 
     if($teams[$i] == $game1[$j]){ 
      $found = true; // if present, set the flag and break. 
      break; 
     } 
    } 
    if(!$found) { // if flag is not set...add. 
     array_push($game2, $teams[$i]); 
    } 
} 
+0

感謝,即時通訊依然有興趣知道爲什麼我的心不是循環工作。有任何想法嗎? – Jonathan 2010-10-03 17:50:20

5

你的循環不起作用,因爲每一個元素時從$teams不等於$game1中的元素,它將$teams元素添加到$game2。這意味着每個元素被多次添加到$game2

使用array_diff代替:

// Find elements from 'teams' that are not present in 'game1' 
$game2 = array_diff($teams, $game1); 
1

您可以使用PHP的array_diff()


$teams = array(1, 2, 3, 4, 5, 6, 7, 8); 
$game1 = array(2, 4, 6, 8); 
$game2 = array_diff($teams,$game1); 

// $game2: 
Array 
(
    [0] => 1 
    [2] => 3 
    [4] => 5 
    [6] => 7 
)