The diff array of a particular key in a multidimensional array

I have two product arrays, both of them are formatted in exactly the same way:

$products = array( [0] => array( ['product_id'] => 33 ['variation_id'] => 0 ['product_price'] => 500.00 ), [1] => array( ['product_id'] => 48 ['variation_id'] => 0 ['product_price'] => 600.00 ), ) 

I would like to be able to return a list of only those products that are not found in the second array, based on the product identifier.

Only those that are NOT found in the second array, and not added to the first ones, will take care of me, so array_diff does not seem to do the trick.

+4
source share
2 answers

A simple foreach loop should be enough:

 <?php $products = array( 0 => array( 'product_id' => 33, 'variation_id' => 0, 'product_price' => 500.00 ), 1 => array( 'product_id' => 48, 'variation_id' => 0, 'product_price' => 600.00 ) ); $products2 = array( 1 => array( 'product_id' => 48, 'variation_id' => 0, 'product_price' => 600.00 ), 2 => array( 'product_id' => 49, 'variation_id' => 0, 'product_price' => 600.00 ) ); $diff = array(); // Loop through all elements of the first array foreach($products2 as $value) { // Loop through all elements of the second loop // If any matches to the current element are found, // they skip that element foreach($products as $value2) { if($value['product_id'] == $value2['product_id']) continue 2; } // If no matches were found, append it to $diff $diff[] = $value; } 

Then the $ diff array will contain only the following value:

 array ( 0 => array ( 'product_id' => 49, 'variation_id' => 0, 'product_price' => 600, ), ) 

Hope this helps!

+3
source

I suspect you want something like array_udiff . This allows you to specify how to compare two arrays using the callback function. You simply create a callback that compares based on the product id.

I think this satisfies what you want, because the array_diff family of functions compares only the first array with the rest, it does not return elements that array2 (or 3 or 4) do not have this array.

 <?php $products = array( 0 => array( 'product_id' => 33, 'variation_id' => 0, 'product_price' => 500.00 ), 1 => array( 'product_id' => 48, 'variation_id' => 0, 'product_price' => 600.00 ) ); $products2 = array( 1 => array( 'product_id' => 48, 'variation_id' => 0, 'product_price' => 600.00 ), 2 => array( 'product_id' => 49, 'variation_id' => 0, 'product_price' => 600.00 ) ); function compare_ids($a, $b) { return $b['product_id'] - $a['product_id']; } var_dump(array_udiff($products, $products2, "compare_ids")); ?> 

Outputs:

 array(1) { [0]=> array(3) { ["product_id"]=> int(33) ["variation_id"]=> int(0) ["product_price"]=> float(500) } } 
+8
source

All Articles