douji2283 2018-11-02 11:54
浏览 73
已采纳

检查数组是否在数组中并在PHP中获得匹配

I have an associative array and wanted to check if an array is in that associative array, If yes, I want to get the matching array.

My associative array look something like this:

 $assoc_array = array(
  array(
   'firstname' => 'John',
   'lastname' => 'Doe',
   'age' => 26
  ),
  array(
   'firstname' => 'Sophia',
   'lastname' => 'Smith',
   'age' => 30
  )
 );

Then if I want to check this array:

 $array = array(
   'firstname' => 'John',
   'lastname' => 'Doe'
 );

It would give me this result:

array(
 'firstname' => 'John',
 'lastname' => 'Doe',
 'age' => 26
);

Any help would be greatly appreciated.

  • 写回答

3条回答 默认 最新

  • douwen1901 2018-11-02 12:12
    关注

    If you loop the array and use array_intersect it will return first and lastname.
    If there is no match it returns empty array.

    This means we can do an easy if on the match if that is true then add the subarray to your new array.

    foreach($assoc_array as $sub){
        $match = array_intersect($sub, $array);
        if($match) $new[] = $sub;
    }
    var_dump($new);
    

    https://3v4l.org/enaXb

    Or condense it to:

    foreach($assoc_array as $sub){
        if(array_intersect($sub, $array)) $new[] = $sub;
    }
    var_dump($new);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.