I have an array
[
[0 => 20, 1 => 36, 3 => 42],
[0 => 21, 1 => 42, 2 => 30],
]
And I have a second array of
[24, 42, 26, 12]
I want to use array_intersect()
to get the values that are the same from each array. What I am having trouble with is figuring out how to properly set up the code to do that. I would hope to have this
[
[42],
[42],
]
To match your example output, you can simply use a foreach
loop. In your example, the 2D array is $array1 and the 1D array is $array2.
$output = [];
foreach ($array1 as $array) {
$output[] = array_intersect($array, $array2);
}
Note that declaring an array with [] is only supported in PHP versions >= 5.4. For PHP versions < 5.4:
$array1 = array(array(20, 36, 42), array(21, 42, 30));
$array2 = array(24, 42, 26, 12);
$output = array();
foreach ($array1 as $array) {
$output[] = array_intersect($array, $array2);
}