dri8163
dri8163
2018-08-03 11:17

从具有匹配值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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • duanchijie2323 duanchijie2323 3年前

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

    点赞 评论 复制链接分享
  • douxuelv7755 douxuelv7755 3年前

    you can achieve this using foreach loop

    foreach( $array1 as $val ){
      $val['user_id'] == $array2['userId'] ? $result[] = $val : ''; 
    }
    echo "<pre>"; print_r( $result );
    
    点赞 评论 复制链接分享
  • douruocai4111 douruocai4111 3年前

    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 )

    点赞 评论 复制链接分享
  • doubaoguo7469 doubaoguo7469 3年前
    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.

    点赞 评论 复制链接分享

相关推荐