Skip to content

Instantly share code, notes, and snippets.

@davidstanley01
Last active May 20, 2016 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidstanley01/3d7e3bc6668289337b75407acb9963b0 to your computer and use it in GitHub Desktop.
Save davidstanley01/3d7e3bc6668289337b75407acb9963b0 to your computer and use it in GitHub Desktop.
compare collections and get values from one that aren't in the other
<?php
// Given 2 collections of nested, indexed arrays,
// find the items in the first array that are not
// found in the second array using a given key
// in this example, find items in $collection1 that
// are not found in $collection2, and return all of
// them as a new collection
$collection1 = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection2 = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Lamp', 'price' => 130],
]);
$diff = $collection1->someMethod($collection2, 'product');
$diff->all();
// [
// ['product' => 'Chair', 'price' => 100]
// ]
///////////////////////////////////////////////////
/// UPDATE
///////////////////////////////////////////////////
$diff = $collection1->filter(function($item) use ($collection2) {
return ! $collection2->contains('product', $item1->get('product'));
});
@jrmadsen67
Copy link

$diff = $collection1->flatten()->diff($collection2->flatten(), 'product');

@davidstanley01
Copy link
Author

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment