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 学习Python如何找兼职
  • ¥15 python结合Matlab仿真忆阻器
  • ¥35 有人会注册whatsaop协议号吗?
  • ¥15 lead dbs 无法导入影像数据
  • ¥15 多目标MPA算法优化编程实现
  • ¥15 反激PWM控制芯片调研
  • ¥15 Python for loop减少运行时间
  • ¥15 fluent模拟物质浓度udf
  • ¥15 Collection contains no element matching the predicate
  • ¥20 冻品电商平台的搜索是怎么实现的