获取后如何取消设置(删除)集合元素? [英] 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 建议忘记() 函数后,我再次检查它,发现我实际上误解了该函数.这正是我所寻找的.
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屋!