取消设置多个数组元素的更好方法

编程入门 行业动态 更新时间:2024-10-28 20:29:11
本文介绍了取消设置多个数组元素的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这里的问题是我有一个包含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']);

更多推荐

取消设置多个数组元素的更好方法

本文发布于:2023-10-26 21:35:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531415.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   数组   元素   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!