Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_diff() with multidimensional arrays

Tags:

arrays

php

I have an array containing rows of associative data.

$array1 = array(     array('ITEM' => 1),     array('ITEM' => 2),     array('ITEM' => 3), ); 

I have a second array, also containing rows of associative data, that I would like to filter using the first array.

$array2 = array(     array('ITEM' => 2),     array('ITEM' => 3),     array('ITEM' => 1),     array('ITEM' => 4), ); 

This feels like a job for array_diff(), but how can I compare the rows exclusively on the deeper ITEM values?

How can I filter the second array and get the following result?

array(3 => array('ITEM' => 4)) 
like image 955
Jonathan Chan Avatar asked Aug 06 '12 01:08

Jonathan Chan


People also ask

How to compare two multidimensional arrays in PHP?

To compare array's structure, You should use identity operator. The only difference(s) between this and my answer is that instead of using == for the elements in the array, it will use === , and with === it checks the order of key value pairs.

What is the difference between associative arrays and multidimensional arrays?

Associative array — An array where each key has its own specific value. Multidimensional array — An array containing one or more arrays within itself.

How do I check if two arrays have the same element in PHP?

Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.

What is multidimensional array explain with example?

A multi-dimensional array is an array with more than one level or dimension. For example, a 2D array, or two-dimensional array, is an array of arrays, meaning it is a matrix of rows and columns (think of a table). A 3D array adds another dimension, turning it into an array of arrays of arrays.


1 Answers

You can define a custom comparison function using array_udiff().

function udiffCompare($a, $b) {     return $a['ITEM'] - $b['ITEM']; }  $arrdiff = array_udiff($arr2, $arr1, 'udiffCompare'); print_r($arrdiff); 

Output:

Array (     [3] => Array         (             [ITEM] => 4         ) ) 

This uses and preserves the arrays' existing structure, which I assume you want.

like image 104
Wiseguy Avatar answered Sep 21 '22 18:09

Wiseguy