从 Laravel 集合中返回特定项目并将其删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23104447/
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
return specific item from a laravel collection and remove it
提问by Friedrich Roell
im trying to map over a collection of query results. Specifically i want to check if an item of that collection suits my closure, returns that item and removes it from that collection. Further more i need to pass parameters with the closure function.
我试图映射一组查询结果。具体来说,我想检查该集合的某个项目是否适合我的关闭,返回该项目并将其从该集合中删除。此外,我需要使用闭包函数传递参数。
$data = Model::where('something', 'stuff')->get();
$res = array();
foreach ($x as $y) {
$res = $data->each("closure function described above with $y");
// do stuff with $res
}
i hope this was clear thank You for Your help cheers.
我希望这很清楚谢谢你的帮助干杯。
回答by The Alpha
You may try something like following, assumed you have some data in $variables
and $y=general
as a type
, so check if the type
is general
then do something with the model that has type general
and then put that model in the $res
array and then remove it from the collection:
您可以尝试以下操作,假设您在$variables
和$y=general
作为 a 中有一些数据type
,因此请检查是否type
是general
然后对具有类型的模型执行某些操作,general
然后将该模型放入$res
数组中,然后将其从集合中删除:
$variables = '...';
$res = array();
$y = 'general'; // for example, $y contains general
$data = Model::where('something', 'stuff')->get();
foreach ($variables as $variable) {
foreach ($data as $key => $model) {
if($model->type == $y) {
// Do something with $model
$res[] = $model;
unset($data[$key]);
}
}
}
Also you may check this article, it maybe helpful to interact with a Collection
object.
您也可以查看这篇文章,它可能有助于与Collection
对象交互。
回答by Sergey Nakhankov
With laravel 5 you can use where method on collection.
使用 Laravel 5,您可以在集合上使用 where 方法。
$data = Model::where('something', 'stuff')->get();
$removedItem = $data->where('key', 'value');
Or if you use Larave 4 you can call filter method on collection
或者,如果您使用 Larave 4,则可以在集合上调用过滤器方法
$removedItem = $data->filter(function($item) use ($removedValue) {
return $item->key == $removedValue;
});
$data = $data->diff($removedItem);
回答by Fuzzyma
To use a variable inside your closure you have to use the keyword 'use' ;).
要在您的闭包中使用变量,您必须使用关键字 'use' ;)。
function($item) use ($y) {
// remove item from collection by key
//using collection.forget($key)
}