2016-11-04 48 views
0

我有許多事情的數組:$arr = array('Apple', 'Pear', 'Pineapple');剔除所有元素,但一個

我想在數組中除了,比如,「蘋果」排除一切。我看了一下使用array_diff,但我不知道如何在我的情況下使用它。

array_diff($arr, array('Apple'));明顯從列表中排除'Apple'。

感謝您的幫助!

編輯:由於需要更多的細節,我必須處理來自我使用的API的數據,它使用一個排除列表來簡化JSON響應。因此,我使用包含可能的選項排除的數組。

+0

什麼?你想要一個元素,你知道你正在尋找的元素的價值? 'in_array' ... –

+0

我需要它在我正在使用的其餘api中排除列表 – madcrazydrumma

+1

需要更多詳細信息。你有什麼工作,那麼你需要什麼不同? – AbraCadaver

回答

1

有是一個更優雅的解決方案:

$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 
) 
+0

這會更優雅,但變量作用域不會找到要在其中使用的函數的參數。即方法參數'$ param1'不能用於'return $ element == $ param1;' – madcrazydrumma

+1

你只是不知道'use'。我編輯了我的帖子。 –

1

假設你正在迭代數組,並且不僅僅是簡單地從數組中刪除'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

+0

修改後將排除內容推送到我自己使用的數組中。謝謝! – madcrazydrumma

0

功能array_intersect()也可能是你的情況有所幫助。例如:

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

將給予相交值的數組:['Apple']

相關問題