dri8163
2018-08-03 11:17
浏览 49
已采纳

从具有匹配值php的多维数组中获取特定数组

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.

图片转代码服务由CSDN问答提供 功能建议

我有2个数组 -

  $ array1 = 
Array  
(
 [0] =>数组
(
 [user_id] => 2 
 [like_status] => 1 
)
 
 [1] =>数组
(  
 [user_id] => 3 
 [like_status] => 1 
)
 
)
 
 $ array2 = 
 
Array 
(
 [isLoggedIn] => 1 \  n [userId] => 3 
)
   
 
 

我的要求是我想获取userId = 3的数组。 $ array1 但我只想获取userID = 3的数组,该数组在$ array2中

我能够进入条件并匹配但不能 获取。

  if(array_search($ array2 ['userId'],array_column($ array1,'user_id'))!== False){
 print_r($  array1); 
} 
   
 
 

但它应该只返回特定的数组。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • duanchijie2323 2018-08-03 11:22
    已采纳

    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'].

    打赏 评论
  • doubaoguo7469 2018-08-03 11:23
    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.

    打赏 评论
  • douruocai4111 2018-08-03 11:34

    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 )

    打赏 评论
  • douxuelv7755 2018-08-03 13:18

    you can achieve this using foreach loop

    foreach( $array1 as $val ){
      $val['user_id'] == $array2['userId'] ? $result[] = $val : ''; 
    }
    echo "<pre>"; print_r( $result );
    
    打赏 评论

相关推荐 更多相似问题