从 PHP 数组中删除黑名单键

问题描述 投票:0回答:4

我有一个关联的数据数组,并且有一个键数组,我想从该数组中删除(同时保持其余键按原始顺序排列 - 这可能不是一个约束)。

我正在寻找一个 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
php arrays key
4个回答
145
投票

$out =
array_diff_key
($data,
array_flip
($bad_keys));

我所做的只是查看数组函数列表,直到找到我需要的那个(

_diff_key
)。


37
投票

解决方案确实是黑暗阿卜索尔尼特提供的解决方案。我想为任何追求类似事情的人提供另一种类似的解决方案,但这个解决方案使用白名单而不是黑名单

$whitelist = array( 'good_key1', 'good_key2', ... ); $output = array_intersect_key( $data, array_flip( $whitelist ) );

这将保留

$whitelist

 数组中的键并删除其余的。


0
投票
这是我为关联数组创建的黑名单函数。

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);
    

0
投票

array_filter() 在我看来更具可读性。

我的做法是这样的:

$data = array_filter($data, function($k) {return !in_array($k, $bad_keys);}, ARRAY_FILTER_USE_KEY);
希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.