【问题标题】:Help with For Loop. Values repeating帮助 For 循环。值重复
【发布时间】:2011-04-20 12:49:28
【问题描述】:
$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,

我该如何改进呢?谢谢

【问题讨论】:

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


    【解决方案1】:

    其他人已经回答了如何使用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]);
        }
    }
    

    【讨论】:

    • 谢谢,我仍然想知道为什么我的循环不起作用。有什么想法吗?
    【解决方案2】:

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

    改用array_diff

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

    【讨论】:

      【解决方案3】:

      你可以使用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
      )

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-21
        • 2018-03-05
        • 1970-01-01
        • 1970-01-01
        • 2015-03-30
        • 2018-07-17
        相关资源
        最近更新 更多