【问题标题】:Remove from collection where exists in another collection从另一个集合中存在的集合中删除
【发布时间】:2017-07-09 22:00:01
【问题描述】:

假设我有 2 个集合,它们都具有 phone 属性:

$contacts = Contact::all();
$optouts = Optout::all();

我想更新$contacts 集合并删除所有选择退出的集合。所以我想删除所有$contacts,其phone存在于$optouts中。

我该怎么做?

【问题讨论】:

    标签: php laravel collections


    【解决方案1】:
    $contacts = Contact::all();
    $optouts = Optout::all()->pluck('phone');
    
    $filtered = $contacts->whereNotIn('phone', $optouts);
    

    更多信息在这里:https://laravel.com/docs/5.4/collections

    【讨论】:

      【解决方案2】:

      一个选项是:

      $phones = $optouts->pluck('phone')->toArray();
      
      $newContacts = $contacts->reject(function ($contact) use ($phones) {
          return in_array($contact->phone, $phones);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多