Jon*_*han 1 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();
Run Code Online (Sandbox Code Playgroud)
如果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 ", ";
}
Run Code Online (Sandbox Code Playgroud)
我期待结果是:
1, 3, 5, 7,
Run Code Online (Sandbox Code Playgroud)
但是,我得到:
1, 1, 1, 1, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
Run Code Online (Sandbox Code Playgroud)
我怎么能改善这个?谢谢
其他人已经回答了如何使用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]);
}
Run Code Online (Sandbox Code Playgroud)
您可以使用标志来修复现有代码:
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
你的循环不起作用,因为每次元素来自$teams不等于元素时$game1,它都会添加$teams元素$game2.这意味着每个元素都被$game2多次添加.
array_diff改为使用:
// Find elements from 'teams' that are not present in 'game1'
$game2 = array_diff($teams, $game1);
Run Code Online (Sandbox Code Playgroud)