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.

  • 写回答

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染