我在集合 https://laravel.com/docs/5.3/collections#method-contains 上使用 Laravel contains
方法。但这对我不起作用。
foreach ($this->options as $option) {
if($options->contains($option->id)) {
dd('test');
}
}
dd($options);
看起来像这样:
Collection {#390
#items: array:1 [
0 => array:3 [
0 => array:7 [
"id" => 10
"slug" => "test"
"name" => "test"
"poll_id" => 4
"created_at" => "2016-11-12 20:42:42"
"updated_at" => "2016-11-12 20:42:42"
"votes" => []
]
1 => array:7 [
"id" => 11
"slug" => "test-1"
"name" => "test"
"poll_id" => 4
"created_at" => "2016-11-12 20:42:42"
"updated_at" => "2016-11-12 20:42:42"
"votes" => []
]
2 => array:7 [
"id" => 12
"slug" => "test-2"
"name" => "test"
"poll_id" => 4
"created_at" => "2016-11-12 20:42:42"
"updated_at" => "2016-11-12 20:42:42"
"votes" => []
]
]
]
}
dd($option->id);
的结果是 10
。
有什么问题吗?或者,还有更好的方法?
原文由 Jamie 发布,翻译遵循 CC BY-SA 4.0 许可协议
您应该将键/值对传递给 contains 方法,该方法将确定给定的对是否存在于集合中。以这种方式使用
contains()
方法: