0

到目前为止,我在 PHP 中构建了这个名为 removeAllValuesMatching 的函数,但我似乎无法让它工作。我传入了两个参数 $arr 和 $value。不知道为什么会这样。任何帮助将不胜感激。这是我到目前为止所拥有的:

<?php 
$arr = array(
   'a' => "one",
   'b' => "two",
   'c' => "three",
   'd' => "two",
   'e' => "four",
   'f' => "five",
   'g' => "three",
   'h' => "two"
);
function removeAllValuesMatching($arr, $value){
 foreach ($arr as $key => $value){
 if ($arr[$key] == $value){
 unset($arr[$key]);
 }
 }
 return $arr = array_values($arr);
 }

print_r(removeAllValuesMatching($arr, "two"));

?>
4

2 回答 2

3

你在$value这里覆盖:

foreach ($arr as $key => $value){

只需重命名它:

foreach ($arr as $key => $val) {
    if ($val == $value) {

但是,从数组中删除元素的更好方法是:

function removeAllValuesMatching(array $arr, $value) {
    $keys = array_keys($arr, $value);
    foreach ($keys as $key) {
        unset($arr[$key]);
    }
    return $arr;
}
于 2012-05-30T18:05:45.953 回答
0

这是我的完整版本,没有变量冲突和缩进:这不是一个选项,您应该始终正确缩进

<?php 
$arr = array(
    'a' => "one",
    'b' => "two",
    'c' => "three",
    'd' => "two",
    'e' => "four",
    'f' => "five",
    'g' => "three",
    'h' => "two"
);

function removeAllValuesMatching($arr, $arg){
    foreach ($arr as $key => $value){
        if ($arr[$key] == $arg){
            unset($arr[$key]);
        }
    }
    return $arr = array_values($arr);
}

print_r(removeAllValuesMatching($arr, "two"));

?>
于 2012-05-30T18:09:42.753 回答