I have 2 arrays -
$array1 =
Array
(
[0] => Array
(
[user_id] => 2
[like_status] => 1
)
[1] => Array
(
[user_id] => 3
[like_status] => 1
)
)
$array2 =
Array
(
[isLoggedIn] => 1
[userId] => 3
)
My requirement is I want to fetch the array where userId = 3. There can be multiple records in $array1
But I only want to fetch the array which have userID = 3, which is in $array2
I am able to get into the condition and match but not able to fetch.
if(array_search($array2['userId'], array_column($array1, 'user_id')) !== False) {
print_r($array1);
}
But it should only return the specific array.
One method is to create a flat array of the userid and use array_intersect to get the matching full arrays.
$userids = array_column($array1, "user_id");
$matching = array_intersect_key($array1, array_intersect($userids, [$array2['user_id']]));
Now $matching will be all the $array1
subarrays where userid is matching $array2['userId']
.
array_search($array2['userId'], array_column($array1, 'user_id'))
Will return the index of a matching item or false
if there is no matching item. You can use this info to grab the array from $array1
.
I.e.
$index = array_search($array2['userId'], array_column($array1, 'user_id')) !== False);
if($index !== false){
print_r($array1[$index]);
}
Note that this assumes that there is only one matching user id in the array - if there are more only the first will be found.
You can do this using foreach also, if you want to like below
foreach ($array1 as $key => $value) {
if($value['user_id'] == $array2['userId'])
{
echo '<pre>'; print_r($value);echo '</pre>';
break;
}
}
Output :
Array ( [user_id] => 3 [like_status] => 1 )
you can achieve this using foreach loop
foreach( $array1 as $val ){
$val['user_id'] == $array2['userId'] ? $result[] = $val : '';
}
echo "<pre>"; print_r( $result );