如何在获取元素后取消设置(删除)集合元素? [英] How to unset (remove) a collection element after fetching it?
问题描述
我有一个集合,我想在获取其某些元素时进行迭代和修改.但是我找不到删除该获取的元素的方法或方法.
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.
@Ohgodwhy提出了got()函数的建议后,我再次对其进行了检查,发现我实际上对该函数有误解.正是我想要的.
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.
因此,对于有效的解决方案,我在if语句内添加了$collection->forget($key)
.
So for working solution I have added $collection->forget($key)
inside the if statement.
以下是使用@Ohgodwhy的解决方案来解决我的问题:
$selected = [];
foreach ($collection as $key => $value) {
if ($collection->selected == true) {
$selected[] = $value;
$collection->forget($key);
}
}
(这只是一个演示)
推荐答案
您想使用->forget()
$collection->forget($key);
链接到忘记方法文档
这篇关于如何在获取元素后取消设置(删除)集合元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!