排除除一个元素以外的所有元素


Excluding all elements but one

我有一个数组:$arr = array('Apple', 'Pear', 'Pineapple');

我想排除数组中除了'Apple'以外的所有内容。我看了一下使用array_diff,但是我不知道如何在我的情况下使用它。

array_diff($arr, array('Apple'));显然将"Apple"从列表中排除。

谢谢你的帮助!

EDIT:由于需要更多的细节,我必须处理来自我正在使用的API的数据,该API采用排除列表来简化JSON响应。因此,我使用包含可能选项的数组来排除。

有一个更优雅的解决方案:

$arr = array('Apple', 'Pear', 'Pineapple');
$newArr = array_filter($arr, function($element) {
        return $element != "Apple";
});
print_r($newArr);

输出为

Array
(
    [1] => Pear
    [2] => Pineapple
)

或者,如果您需要排除除Apple以外的所有内容,只需将return语句更改为return $element == "Apple";

你说这不是一个优雅的解决方案,因为

变量作用域不会在那里找到要使用的函数形参。即方法参数$param1不能用于返回$element == $param1;

但它可以。你只是不知道use:

$arr = array('Apple', 'Pear', 'Pineapple');
$param = "Apple";
$newArr = array_filter($arr, function($element) use ($param) {
        return $element != $param;
});

现在,$newArr仍然包含请求的

Array
(
    [1] => Pear
    [2] => Pineapple
)

假设您正在遍历数组,而不仅仅是从数组中简单地删除'Apple'值…你可以在循环中添加一个条件检查,用于检查任何值。

foreach($arr as $key => $value){
    if($value != 'Apple'){ //array value is not 'Apple,' do something
        //do something
    }
}

或者,您可以使用一个简单的函数复制数组并排除您想要的任何内容:

<?php
function copy_arr_exclude_byVal(array &$arrIn, ...$values){
    $arrOut = array();
    if(isset($values) && count($values) > 0){
        foreach($arrIn as $arrKey => $arrValue){
            if(!in_array($arrValue, $values)){
                $arrOut[] = $arrValue;
                //to keep original key names: $arrOut[$arrKey] = $arrValue;
            }
        }
    }else{
        $arrOut = $arrIn;
        return($arrOut);//no exclusions, copy and return array
    }
    return($arrOut);
}

/* TEST */
$testArr = array('test1', 'test2', 'foo', 'bar');
$newArr = copy_arr_exclude_byVal($testArr, 'foo');
echo var_dump($newArr);

还可以查看本机函数array_filter(): http://php.net/manual/en/function.array-filter.php

函数array_intersect()也可能对您的情况有所帮助。例如:

array_intersect(array('Apple', 'Pear', 'Pineapple'), array('Apple', 'Watermelon'));

将给出一个值相交的数组:['Apple']