﻿ How to get the intersection of an array of multidimensional arrays?

# How to get the intersection of an array of multidimensional arrays?

I have an array of multidimentional arrays. Each array represents a result set from a search. I am having trying to figure out how to filter this set of data to only include arrays that are present in each array.

Note: The index's shown below each represent multidimentional arrays. Each array has a deeply nested `Id` key that can be used for comparison.

The `Id` is located at:

`\$reference_variable['data']['Id'][0]`

For example,

``````array(
array([0], [19], [21], [148]),
array([2], [21], [32], [44], [432], [549]),
array([13], [21], [148])
)
``````

Should return:

``````array(
[21]
)
``````

and:

``````array(
array([0], [12], [15]),
array([2], [21], [32], [44], [432], [549]),
array([13], [21], [148])
)
``````

Should return:

``````array(
[]
)
``````

What is the best way to handle this? array_intersect does not work well with multidimensional arrays.

I've already tried storing all `Id`s in an array, and using `array_count_values` to find duplicate `Id`s, and then use `array_filter` to compare if the `Id` of the current array was equal to any of the duplicate `Id`'s.

But that turned out to be totally wrong since this method would allow:

``````array(
array([0], [19], [21], [148]),
array([2], [21], [32], [44], [432], [549]),
array([13], [21], [148])
)
``````

To return:

``````array(
[21, 148]
)
``````

Which is not the intersection of all arrays.

Just store the indexes of the first array in an array. Check for matching indexes on the second array and store those in a second array A2. Check for matches between the second stored array ( A2 ) and the third array. Call it A3 for consistency ( A3 ). This is your answer.

Maybe 10-20 lines of code.

This was the answer in my case:

``````\$params = array_merge(\$array_of_arrays, array('array_compare'));

\$intersection = call_user_func_array('array_uintersect', \$params);

function array_compare(\$a1, \$a2)
{
if (\$a1 === \$a2) {
return 0;
}
if (\$a1 > \$a2) {
return 1;
}
return -1;
}
``````

Credit: