Unset elements using array keys

女生的网名这么多〃 提交于 2019-12-11 21:01:32

问题


So I need to delete some array elements, is there easy way not including foreach loop?

$privateData = ['id', 'date', 'whatever'];

foreach($privateData as $privateField) {
    unset($request[$privateField]);
}

I tried to search array_map array_walk functions for examples but I did not find any.


回答1:


$result = array_diff_key($request, array_flip(['id', 'date', 'whatever']));



回答2:


Here's how you do it using array_map:

array_map(function($privateField) use ($request) {
    unset($request[$privateField]);
}, $privateData);

You need to use the use option to access $request from the outer scope.

I don't know why you'd want to do it this way. The foreach loop is much clearer. But since you asked.



来源:https://stackoverflow.com/questions/25033456/unset-elements-using-array-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!