在PHP中,如何删除数组中的项目,其中的键可以方便地在另一个数组中找到?

时间:2017-08-15 06:45:26

标签: php arrays

我有两个数组:

$array = new Array('id'=>1, 'name'=>'Peter', 'sex'=>'male', 'age'=>25);

$excludes = new Array('sex', 'age');

我想得到以下结果:

$array = new Array('id'=>1, 'name'=>'Peter');

将删除在数组$ excludes中找到键的项目。

如何方便地实现这一目标?

2 个答案:

答案 0 :(得分:4)

只需使用array_diff_keyarray_flip函数:

// $arr is your initial array (besides, don't give `$array` name to arrays)
$result = array_diff_key($arr, array_flip($excludes));
print_r($result);

输出:

Array
(
    [id] => 1
    [name] => Peter
)

答案 1 :(得分:1)

function removeExcludesFromArray($input,$expludes) {
    $newArray = array(); // Create a new empty array
    foreach($array as $inputKey => $inputElement) { // loop your original array
        if(!array_key_exists($inputKey,$excludes)) { // check if key exists
             $newArray[$inputKey] = $inputElement; // add on demand
         }
     }

     return $newArray; // return the result
}


// Call the function
$array = removeExcludesFromArray($array,$excludes);