dsdtszi0520538 2017-01-08 16:13 采纳率: 100%
浏览 7
已采纳

检查数组是否在两个多维数组中

I have two multidimensional arrays:

Haystack

$haystack = array (
  0 => array (
    "child_element_id" => 11
    "answer_id" => 15
  ),
  1 => array (
    "child_element_id" => 12
    "answer_id" => 17
  ),
  2 => array (
    "child_element_id" => 13
    "answer_id" => 21
  )
)

Needle

 $needle = array (
  0 => array (
    "child_element_id" => 12
    "answer_id" => 17
  ),
  1 => array (
    "child_element_id" => 13
    "answer_id" => 21
  )
)

I want to check if all the key values from array "Needle" exists in the array "Haystack". What's the best practice for this? Thank you!

  • 写回答

3条回答 默认 最新

  • dounayan3643 2017-01-09 00:07
    关注

    Pretty easy using in_array() since needle can be an array:

    $found = 0;
    foreach($needle as $array) {
        if(in_array($array, $haystack, true)) {
            $found++;
        }
    }
    if($found === count($needle)) {
        echo 'all needles were found in haystack';
    }
    

    Or maybe:

    $found = true;
    foreach($needle as $array) {
        if(!in_array($array, $haystack, true)) {
            $found = false;
            break;
        }
    }
    if($found) {
        echo 'all needles were found in haystack';
    }
    

    You could even use array_search() as you can use an array for needle as well, no need to run two loops.

    Using serialize():

    if(count(array_map('unserialize',
             array_intersect(array_map('serialize', $needle), 
                             array_map('serialize',$haystack)))) == count($needle))
    {
                                 echo 'all needles were found in haystack';
    }
    
    • serialize() the inner arrays of both arrays and compute the intersection (common inner arrays)
    • unserialize() the result and compare the count() with the count of $needle
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料