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.

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.

So for working solution I have added $collection->forget($key) inside the if statement.

Below is the working solution of my problem, using @Ohgodwhy's solution:

$selected = [];
foreach ($collection as $key => $value) {
if ($collection->selected == true) {
$selected[] = $value;
$collection->forget($key);
}
}

(this is just a demonstration)

201572 次浏览

您会希望使用 ->forget()

$collection->forget($key);

连接到 forget method documentation

或者你可以使用 reject 方法

$newColection = $collection->reject(function($element) {
return $item->selected != true;
});

pull 方法

$selected = [];
foreach ($collection as $key => $item) {
if ($item->selected == true) {
$selected[] = $collection->pull($key);
}
}

Laravel Collection implements the PHP ArrayAccess interface (which is why using foreach is possible in the first place).

如果您已经有了密钥,那么只需使用 PHPunset即可。

我更喜欢这样,因为它清楚地修改了集合,并且容易记住。

foreach ($collection as $key => $value) {
unset($collection[$key]);
}

如果您知道您取消设置的键,那么直接用逗号放置 分居了

unset($attr['placeholder'], $attr['autocomplete']);

对于迭代遍历集合并在循环内部操作甚至该集合的内容的解决方案,我并不满意。这可能导致意想不到的行为。

另见此处: https://stackoverflow.com/a/2304578/655224和注释中给定的链接 http://php.net/manual/en/control-structures.foreach.php#88578

因此,当使用 foreach时,它似乎还可以,但恕我直言,更易读和简单的解决方案是过滤您的集合到一个新的。

/**
* Filter all `selected` items
*
* @link https://laravel.com/docs/7.x/collections#method-filter
*/
$selected = $collection->filter(function($value, $key) {
return $value->selected;
})->toArray();

You can use methods of 收集 like , 忘记, reject etc.

但是每个 Collection方法都返回一个全新的 Collection 实例。

文件链接: https://laravel.com/docs/8.x/collections#introduction