我有两个数组:
$array = new Array('id'=>1, 'name'=>'Peter', 'sex'=>'male', 'age'=>25);
$excludes = new Array('sex', 'age');
我想得到以下结果:
$array = new Array('id'=>1, 'name'=>'Peter');
将删除在数组$ excludes中找到键的项目。
如何方便地实现这一目标?
答案 0 :(得分:4)
只需使用array_diff_key
和array_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);