我有一个关联的数据数组,并且有一个键数组,我想从该数组中删除(同时保持其余键按原始顺序排列 - 这可能不是一个约束)。
我正在寻找一个 one liner 的 php 来做到这一点。
我已经知道如何循环遍历数组,但似乎应该有一些
array_map
与 unset
或 array_filter
解决方案就在我的掌握之外。
我四处搜寻了一下,但发现没有什么太简洁的。
要明确的是,这是在一行中解决的问题:
//have this example associative array of data
$data = array(
'blue' => 43,
'red' => 87,
'purple' => 130,
'green' => 12,
'yellow' => 31
);
//and this array of keys to remove
$bad_keys = array(
'purple',
'yellow'
);
//some one liner here and then $data will only have the keys blue, red, green
解决方案确实是黑暗阿卜索尔尼特提供的解决方案。我想为任何追求类似事情的人提供另一种类似的解决方案,但这个解决方案使用白名单而不是黑名单:
$whitelist = array( 'good_key1', 'good_key2', ... );
$output = array_intersect_key( $data, array_flip( $whitelist ) );
这将保留
$whitelist
数组中的键并删除其余的。
if(!function_exists('array_blacklist_assoc')){
/**
* Returns an array containing all the entries from array1 whose keys are not present in any of the other arrays when using their values as keys.
* @param array $array1 The array to compare from
* @param array $array2 The array to compare against
* @return array $array2,... More arrays to compare against
*/
function array_blacklist_assoc(Array $array1, Array $array2) {
if(func_num_args() > 2){
$args = func_get_args();
array_shift($args);
$array2 = call_user_func_array('array_merge', $args);
}
return array_diff_key($array1, array_flip($array2));
}
}
$sanitized_data = array_blacklist_assoc($data, $bad_keys);
array_filter() 在我看来更具可读性。
我的做法是这样的:
$data = array_filter($data, function($k) {return !in_array($k, $bad_keys);}, ARRAY_FILTER_USE_KEY);
希望这有帮助!