Home > Back-end >  Laravel collection find common items
Laravel collection find common items

Time:04-15

I am trying to find the common items existing in a collection like the following one:

Laravel collection

I would like to end up with a new collection that contains the 928 and the 895 (common items between the key 95 and the key 94).

How can I do it?

I have an array of keys, but I don't understand how to loop over the keys AND the values without create a mess of variables and additional arrays:

foreach ($ids as $id) {
    $item_ids->each(function ($item, $key) {
    
    });
}

CodePudding user response:

Well, I ended up with that solution:

 $all  = $item_ids->all();

 $list = [];
 foreach ($all as $single) {
        $list[] = $single->toArray();
 }
 $commonItems = collect(call_user_func_array('array_intersect', $list));

CodePudding user response:

So, this is a more laravel approach:

           $items = $item_ids['items']->map(function ($item){
        $collection[] = $item['items'];
        return collect($collection)->duplicates();
    });

  • Related