laravel 获取后如何取消设置(删除)集合元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37588515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to unset (remove) a collection element after fetching it?
提问by Skeletor
I have a collection which I want to iterate and modify while I fetch some of its elements. But I could't find a way or method to remove that fetched element.
我有一个集合,我想在获取其中的一些元素时对其进行迭代和修改。但是我找不到删除该获取元素的方法或方法。
$selected = [];
foreach ($collection as $key => $value) {
if ($collection->selected == true) {
$selected[] = $value;
unset($value);
}
}
This is just a representation of my question for demonstration.
这只是我的演示问题的代表。
After @Ohgodwhy advice the forget() function I checked it again and saw that I actually misunderstood the function. It was exactly as I was looking for.
在@Ohgodwhy 建议忘记() 函数后,我再次检查它,发现我实际上误解了该函数。这正是我所寻找的。
So for working solution I have added $collection->forget($key)
inside the if statement.
所以对于工作解决方案,我$collection->forget($key)
在 if 语句中添加了。
Below is the working solution of my problem, using @Ohgodwhy's solution:
以下是我的问题的工作解决方案,使用@Ohgodwhy 的解决方案:
$selected = [];
foreach ($collection as $key => $value) {
if ($collection->selected == true) {
$selected[] = $value;
$collection->forget($key);
}
}
(this is just a demonstration)
(这只是一个演示)
回答by Ohgodwhy
You would want to use ->forget()
你想用 ->forget()
$collection->forget($key);
Link to the forget method documentation
链接到忘记方法文档
回答by huuuk
回答by andrewtweber
Laravel Collection
implements the PHP ArrayAccess
interface (which is why using foreach
is possible in the first place).
LaravelCollection
实现了 PHPArrayAccess
接口(这就是为什么foreach
首先可以使用)。
If you have the key already you can just use PHP unset
.
如果您已经拥有密钥,则可以使用 PHP unset
。
I prefer this, because it clearly modifies the collection in place, and is easy to remember.
我更喜欢这个,因为它清楚地修改了集合,并且很容易记住。
foreach ($collection as $key => $value) {
unset($collection[$key]);
}
回答by algorhythm
I assumed that $collection->selected
means $value->selected
and then I would refactor the complete code like this:
我认为这$collection->selected
意味着$value->selected
然后我会像这样重构完整的代码:
/**
* Filter all `selected` items
*
* @link https://laravel.com/docs/5.8/collections#method-filter
*/
$selected = $collection->filter(function($value, $key) {
return $value->selected;
})->toArray();
回答by Kaushik shrimali
If you know the key which you unset then put directly by comma separated
如果您知道未设置的密钥,则直接用逗号分隔
unset($attr['placeholder'], $attr['autocomplete']);