取消设置多个数组元素的更好方法 [英] Better way to unset multiple array elements

查看:87
本文介绍了取消设置多个数组元素的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的问题是我有一个包含17个元素的数组.我想获取需要的元素一段时间,然后将其从数组中永久删除.

The deal here is that I have an array with 17 elements. I want to get the elements I need for a certain time and remove them permanently from the array.

代码如下:

$name = $post['name'];
$email = $post['email'];
$address = $post['address'];
$telephone = $post['telephone'];
$country = $post['country'];

unset($post['name']);
unset($post['email']);
unset($post['address']);
unset($post['telephone']);
unset($post['country']);

是的,代码很丑陋,无需扑朔迷离.如何使它看起来更好?

Yes the code is ugly, no need to bash. How do I make this look better?

推荐答案

它看起来像函数 extract() 将是您尝试做的更好的工具(假设它从数组中提取所有键/值,并将它们分配给与本地作用域中的键具有相同名称的变量).提取内容后,假设未包含任何其他内容,您可以取消设置整个$post.

但是,要真正回答您的问题,您可以创建要删除并遍历的键的数组,显式取消设置它们...

However, to actually answer your question, you could create an array of the keys you want to remove and loop through, explicitly unsetting them...

$removeKeys = array('name', 'email');

foreach($removeKeys as $key) {
   unset($arr[$key]);
}

...或者您可以将变量指向删除了键的新数组...

...or you could point the variable to a new array that has the keys removed...

$arr = array_diff_key($arr, array_flip($removeKeys));

...或将所有数组成员传递给unset() ...

...or pass all of the array members to unset()...

unset($arr['name'],  $arr['email']);

这篇关于取消设置多个数组元素的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆