1
$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,

我该如何改进呢?谢谢

4

3 回答 3

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]);
    }
}
于 2010-10-03T17:48:32.543 回答
5

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

改用array_diff

// Find elements from 'teams' that are not present in 'game1'
$game2 = array_diff($teams, $game1);
于 2010-10-03T17:49:16.823 回答
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
)
于 2010-10-03T17:51:21.070 回答