【问题标题】:Laravel collection containsLaravel 集合包含
【发布时间】:2017-03-26 19:19:25
【问题描述】:

我在集合 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

可能出了什么问题?还是有更好的办法?

【问题讨论】:

  • 不知何故,5年多过去了,没有人能正确回答这个问题。 dd() 的输出清楚地显示该集合包含一个项目:一个数组。当然尝试在数组上使用Collection::contains() 会失败!
  • 即使接受的答案有效,它也只是在问“这个集合的 id 是否等于它自己的 id?”当然可以!我觉得我正在服用疯狂的药丸等。

标签: php laravel collections


【解决方案1】:

您应该将键/值对传递给 contains 方法,这将 确定给定对是否存在于集合中。这样使用contains()方法:

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

【讨论】:

    【解决方案2】:

    contains 方法确定集合是否包含给定项目。 基本上可以使用三种方式:

    • 只需检查项目
    $collection = collect(['name' => 'Sarah', 'age' => 23]);
    
    $collection->contains('Desk');
    
    // false
    
    $collection->contains('Sarah');
    
    // true
    
    • 检查键/值对:
    $collection = collect([
        ['name' => 'Sarah', 'age' => 23],
        ['name' => 'Vicky', 'age' => 34],
    ]);
    
    $collection->contains('name', 'Hank');
    
    // false
    
    • 通过回调函数检查:
    $collection = collect([3, 5, 7, 9, 11]);
    
    $collection->contains(function ($value, $key) {
        return $value < 2;
    });
    
    // false
    

    现在,对于您的问题,我们将使用第二类,即:

    foreach ($this->options as $option) {
       // here id is key and $option->id is value
      if($option->contains('id', $option->id)) {
          dd('test');
      }
    }
    

    链接到docs

    【讨论】:

    • 这实际上是 > 5 年前发布的确切答案。
    【解决方案3】:

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

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

    Docs

    【解决方案4】:
    foreach ($this->options as $option) {
        if(!$options->flatten(1)->where('id',$option->id)->isEmpty()) {
            dd('test');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 1970-01-01
      • 2018-12-10
      • 2015-01-30
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多