John Davidson

php - Get the intersection of two arrays with different structure

0 comments
Message:


I'm having two arrays and try to get the user_id exists in both , but I cant use array intersect function , I wasn't able to do it unless i used loop inside loop and I guess that is so bad because arrays will be too big , Is there any solution? or way to make array intersect work ..


https://i.stack.imgur.com/6rlZF.jpg



My Answer:
You can achieve this by using the array_intersect function along with array_column to extract the user_id values from each array. Here's an example:

php
$array1 = [
['user_id' => 1, 'name' => 'John'],
['user_id' => 2, 'name' => 'Jane'],
['user_id' => 3, 'name' => 'Alice']
];

$array2 = [
['id' => 1, 'username' => 'john_doe'],
['id' => 3, 'username' => 'alice_smith'],
['id' => 4, 'username' => 'bob_jones']
];

$userIds1 = array_column($array1, 'user_id');
$userIds2 = array_column($array2, 'id');

$intersection = array_intersect($userIds1, $userIds2);

print_r($intersection);


This will output:


Array
(
[0] => 1
[1] => 3
)


This way, you can get the intersection of user_id values from both arrays without having to use nested loops.

Rate this post

3 of 5 based on 3971 votes

Comments




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