Currently going crazy on how to do this, basicly I have a multidimensional array and need a code to check all values and if value exists in all arrays than to return the result.
Parents visitPoints,islands,animals will always exist, although some times empty, the second level columns are dynamic so keys 20,35,57 change and there content.
$array = [
'visitPoints'=>[
20=>[2,5,6,8,10,11],
35=>[2,5,6],
57=>[1],
],
'islands'=>[
20=>[5,10,11],
35=>[5,6]
],
'animals'=>[
20=>[5,11],
35=>[]
]
];
And the result I’m looking for is this:
$result = [
20=>[5,11],
35=>[],
57=>[]
];
was playing around with call_user_func_array(‘array_intersect’, $array) but could not get the result I’m looking for.
Here is the sample link: https://3v4l.org/meX5p
2
Answers
Perhaps something like this? Test it here.
EDIT
I noticed that this will keep the indices from the third level of the initial array (in this case, indices
1
and5
). If you don’t mind that, you can use the example as it was given. If you do need to reset the indices (i.e.0 => 5
,=> 11
, etc), then you can do something like this:Isolate the first subset and apply it to the result, then iterate the remaining subsets by following the result array’s keys and filter the respective rows with
array_intersect()
falling back to an empty array when a result row is not found for a respective key. (Demo)I’ll include null coalescing on the result in case the input array is empty.