Last active
May 20, 2016 21:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$diff = $collection1->flatten()->diff($collection2->flatten(), 'product');