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条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容