php Laravel:在集合过滤上传递额外的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24597499/
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
Laravel : Passing extra parameter on Collection filtering
提问by Joel Hernandez
the idea it's quite simple, however I have not yet been able to materialize it.
这个想法很简单,但是我还没有能够实现它。
Here's the code
这是代码
(I've changed the name of the variables to describe their use)
(我已经更改了变量的名称来描述它们的用途)
$games = Game::all();
$games_already_added = $member->games()->lists('id');
$games = $games->filter(function($game){
global $games_already_added;
if(!in_array($game->id,$games_already_added)){
return true;
}
});
When the code is executed I receive the error
执行代码时,我收到错误
in_array() expects parameter 2 to be array, null given
in_array() expects parameter 2 to be array, null given
I have verified that the variable $games_already_added
is defined on the outer scope and contains items.
我已经验证该变量$games_already_added
是在外部作用域上定义的并且包含项目。
Is there any way I could pass the $games_already_added
variable as a parameter on the collection's filter function ?
有什么办法可以将$games_already_added
变量作为参数传递给集合的过滤器函数吗?
Any kind of suggestion's or guidance are highly appreciated !
任何形式的建议或指导都非常感谢!
Thank you!
谢谢!
回答by Jarek Tkaczyk
It's not global, but use
that works with a Closure:
它不是全局的,但use
适用于闭包:
$games = $games->filter(function($game) use ($games_already_added) {
if(!in_array($game->id,$games_already_added)){
return true;
}
});
回答by Joel Hinz
This isn't strictly what you're trying to do - but it looks like it's what you want to achieve.
严格来说,这并不是您想要做的事情 - 但看起来这就是您想要实现的目标。
$games_already_added = $member->games()->lists('id');
$games = Game::whereNotIn('id', $games_already_added)->get();
But if you really want to do the filtering, @deczo's answer is the way to go.
但如果你真的想做过滤,@deczo 的答案就是要走的路。