帮助For循环。值重复

时间:2010-10-03 17:45:12

标签: php arrays loops for-loop nested-loops

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

如果teams[x]不在game1中,则插入game2

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,

我怎样才能改善这一点?感谢

3 个答案:

答案 0 :(得分: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]);
    }
}

答案 1 :(得分:5)

您的循环不起作用,因为每次$teams中的元素不等于$game1中的元素时,它都会将$teams元素添加到$game2。这意味着每个元素都会多次添加到$game2

改为使用array_diff

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

答案 2 :(得分: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
)
相关问题