Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using array_intersect on a multi-dimensional array

I have two arrays that both look like this:

Array (     [0] => Array         (             [name] => STRING             [value] => STRING         )      [1] => Array         (             [name] => STRING             [value] => STRING         )      [2] => Array         (             [name] => STRING             [value] => STRING         ) ) 

and I would like to be able to replicate array_intersect by comparing the ID of the sub arrays within the two master arrays. So far, I haven't been successful in my attempts. :(

like image 309
Nathan Avatar asked Apr 13 '11 17:04

Nathan


People also ask

Can C language handle multidimensional arrays?

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];

Which library can be used to support multidimensional array?

numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object and tools for working with these arrays.

Can multi-dimensional arrays be indexed?

Indexing multi-dimensional arraysMulti-dimensional arrays are indexed in GAUSS the same way that matrices are indexed, using square brackets [] . Scanning above, you can see that the value of the element at the intersection of the third row and second column of x1 is 8.


2 Answers

Use array_uintersect() to use a custom comparison function, like this:

$arr1 = array(            array('name' => 'asdfjkl;', 'value' => 'foo'),            array('name' => 'qwerty', 'value' => 'bar'),            array('name' => 'uiop', 'value' => 'baz'),         );  $arr2 = array(            array('name' => 'zxcv', 'value' => 'stuff'),            array('name' => 'asdfjkl;', 'value' => 'foo'),            array('name' => '12345', 'value' => 'junk'),            array('name' => 'uiop', 'value' => 'baz'),         );  $intersect = array_uintersect($arr1, $arr2, 'compareDeepValue'); print_r($intersect);  function compareDeepValue($val1, $val2) {    return strcmp($val1['value'], $val2['value']); } 

which yields, as you would hope:

Array (     [0] => Array         (             [name] => asdfjkl;             [value] => foo         )      [2] => Array         (             [name] => uiop             [value] => baz         )  ) 
like image 195
Wiseguy Avatar answered Oct 03 '22 17:10

Wiseguy


function compareDeepValue($val1, $val2) {    return strcmp($val1['value'], $val2['value']); } 

Be sure that val2 key is existing in val1 array, because the function is ordering array first. Very strange.

like image 39
ScreamZ Avatar answered Oct 03 '22 17:10

ScreamZ