这里的问题是我有一个包含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']);更多推荐
取消设置多个数组元素的更好方法
发布评论