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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大