我有一些我创建的代码,它应该可以查看字符串数组中是否存在某些内容。如果它不存在,我想删除该数组的元素。我认为我们使用unset
执行此操作,但它似乎无法正常工作。心灵帮助?
echo '<br>size of $games before end-check: '.sizeof($games);
foreach ($games as $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
unset($game);
}
}
echo '<br>size of $games after end-check: '.sizeof($games);
输出:
size of $games before end-check: 2
end of game found
end of game not found. incomplete game
size of $games after end-check: 2
答案 0 :(得分:4)
因为你取消了变量$ game的设置,而不是数组中的元素。试试这个:
echo '<br>size of $games before end-check: '.sizeof($games);
foreach ($games as $index => $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
unset($games[$index]);
}
}
echo '<br>size of $games after end-check: '.sizeof($games);
答案 1 :(得分:2)
你必须取消游戏指数。
foreach ($games as $key => $value) {
// all your logic here, performed on $value
unset($games[$key]);
}
答案 2 :(得分:2)
这仅仅取消了对元素的本地引用。你需要直接引用数组。
foreach($games as $key => $game)
unset($games[$key]);
答案 3 :(得分:0)
这不起作用:foreach
创建一个新变量,复制旧变量。取消设置它将对原始值无效。同样,将其作为参考也不会起作用,因为只会删除参考。
最好的方法是使用array_filter
:
$games = array_filter($games, function($game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
return true;
}
else {
echo "<br>end of game not found. incomplete game";
return false;
}
});
这使用PHP 5.3中引入的匿名函数语法。如果函数返回true
,则保留元素;如果它返回false
,则删除该元素。
答案 4 :(得分:0)
您也可以参考:
foreach($games as &$game) {
unset($game);
}
通过这种方式,您还可以更改$game
(例如$game .= " blah";
)并修改原始数组。
答案 5 :(得分:0)
您可以将array_splice
与递增增长的索引变量结合使用,以从数组中删除当前项:
$index = 0;
foreach ($games as $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
array_splice($games, $index, 1);
}
$index++;
}