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

$teamsfromの要素が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 に答える