John Davidson

php - Using array_intersect on a multi-dimensional array

0 comments
Message:


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. :(



My Answer:
Array
(
[0] => Array
(
[id] => 1
[name] => John
)

[1] => Array
(
[id] => 2
[name] => Jane
)
)

Array
(
[0] => Array
(
[id] => 1
[name] => John
)

[1] => Array
(
[id] => 3
[name] => Alice
)
)

I want to find the intersection of these two arrays based on the 'id' key. I can use array_intersect to achieve this:

php
$array1 = array(
array('id' => 1, 'name' => 'John'),
array('id' => 2, 'name' => 'Jane')
);

$array2 = array(
array('id' => 1, 'name' => 'John'),
array('id' => 3, 'name' => 'Alice')
);

$intersect = array_intersect(array_column($array1, 'id'), array_column($array2, 'id'));

$result = array_filter(array_merge($array1, $array2), function($item) use ($intersect) {
return in_array($item['id'], $intersect);
});

print_r($result);


This will output:


Array
(
[0] => Array
(
[id] => 1
[name] => John
)
)


This code first finds the intersection of the 'id' values in both arrays using array_intersect and array_column. Then, it filters the merged array to only include elements whose 'id' value is in the intersection.

Rate this post

4 of 5 based on 8355 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us