簡體   English   中英

在PHP中從數組中刪除黑名單鍵

[英]Remove blacklist keys from array in PHP

我有一個關聯的數據數組,我有一個我想從該數組中刪除的鍵數組(同時保持原始順序中的其余鍵 - 不是這可能是一個約束)。

我要尋找的PHP的一個襯墊做到這一點。
我已經知道如何循環遍歷數組,但似乎應該有一些array_map with unsetarray_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

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

我所做的只是查看數組函數列表,直到找到我需要的_diff_key_diff_key )。

解決方案確實是由Niet the Dark Absol提供的解決方案。 我想為類似的人提供另一個類似的解決方案,但是這個使用白名單而不是黑名單

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM