[英]Using in_array on collections
I need to check for a name in an array of names but I having trouble passing an array instead of a collection to the in_array() method. 我需要检查名称数组中的名称,但是我无法将数组而不是集合传递给in_array()方法。
My blade code looks something like this 我的刀片代码看起来像这样
@foreach($ecn->areas as $area)
{{ $area->area }}:<br>
<ul>
@foreach($area->people as $person)
@if(in_array($person, $ecn->signatures->name ))
<li><del>{{ $person }}</del></li>
@else
<li>{{ $person }}</li>
@endif
@endforeach
</ul>
@endforeach
I know my problem is in the way im trying to access the list of signatures. 我知道我的问题是我试图访问签名列表的方式。
@if(in_array($person, $ecn->signatures->name ))
I can access them in another part of the page doing this 我可以在页面的另一部分访问它们
@foreach($ecn->signatures as $signature)
{{ $signature->name }}<br>
@endforeach
and everything is fine. 一切都很好。
How can I access and pass the list of signatures as an array in this scenario? 在这种情况下,如何访问并将签名列表作为数组传递?
If you want to use in_array()
version for Laravel Collections then you can use: 如果您想为Laravel Collections使用
in_array()
版本,那么您可以使用:
$collection->contains($needle)
It woks just like in_array
. 它就像
in_array
一样。
If $needle
is an integer, an id
for example, don't forget to pluck first, like so: 如果
$needle
是一个整数,例如一个id
,请不要忘记先插入,如下所示:
$collection->pluck('id')->contains($needle)
You can use the lists
or pluck
method on the signatures collection to get a new collection of all the names. 您可以使用签名集合上的
lists
或pluck
方法来获取所有名称的新集合。 From there, you can either use the contains()
method on the collection, or you can use the all()
method to turn the collection into an array and use in_array
directly. 从那里,您可以在集合上使用
contains()
方法,也可以使用all()
方法将集合转换为数组并直接使用in_array
。
I would suggest doing this outside of the foreach loop, so you're not generating this new collection and array every iteration. 我建议在foreach循环之外执行此操作,因此您不会在每次迭代时生成此新集合和数组。
Array: 阵:
// controller
$names = $ecn->signatures->lists('name')->all();
// blade
@if(in_array($person, $names))
Collection: 采集:
// controller
$names = $ecn->signatures->lists('name');
// blade
@if($names->contains($person))
You can also use contains()
with a closure, which would let you get away with not creating an intermediate collection, but it's a little harder to read: 你也可以使用带有闭包的
contains()
,它可以让你逃避不创建一个中间集合,但它有点难以阅读:
Contains with closure: 包含封闭:
// blade
@if($ecn->signatures->contains(function ($key, $value) use ($person) {
return $value->name == $person;
}))
As per Laravel Docs 根据Laravel Docs
The
get
method returns an array of results where each result is an instance of the PHPStdClass
object.get
方法返回一个结果数组,其中每个结果都是PHPStdClass
对象的一个实例。
So you must convert your stdClass object to a array in your controller itself. 因此,您必须将stdClass对象转换为控制器本身的数组。
foreach ($ecn->signatures as $signature)
$nameArray[] = $signature->name;
and then you can use in_array in the blade template 然后您可以在刀片模板中使用in_array
@if(in_array($person, $nameArray))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.