php Laravel 集合包含

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40566972/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:11:55  来源:igfitidea点击:

Laravel collection contains

phplaravelcollections

提问by Jamie

I'm using the Laravel containsmethod on a collection https://laravel.com/docs/5.3/collections#method-contains. But it does not work for me.

我在contains集合https://laravel.com/docs/5.3/collections#method-contains上使用 Laravel方法。但它对我不起作用。

foreach ($this->options as $option) {
    if($options->contains($option->id)) {
        dd('test');
    }
}

dd($options);looks like this:

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" => []
      ]
    ]
  ]
}

Result of dd($option->id);is 10.

结果dd($option->id);10

What could be wrong? Or is there a better way?

可能有什么问题?或者,还有更好的方法?

回答by Saumya Rastogi

You should pass a key / value pair to the contains method, which will determine if the given pair exists in the collection.

您应该将一个键/值对传递给 contains 方法,该方法将确定给定的对是否存在于集合中。

You should use contains()method in this way:

您应该contains()以这种方式使用方法:

foreach ($this->options as $option) {
  // Pass key inside contains method
  if($option->contains('id', $option->id)) {
      dd('test');
  }
}

Hope this helps

希望这可以帮助

回答by Jan Willem

Use the following, which tells Laravel you want to match the 'id':

使用以下命令告诉 Laravel 你想要匹配 'id':

$options->contains('id', $option->id);

Docs

文档

回答by Don

foreach ($this->options as $option) {
    if(!$options->flatten(1)->where('id',$option->id)->isEmpty()) {
        dd('test');
    }
}