array_intersect 不同的值

array_intersect different value

我使用 array_intersect 来比较 2 个数组

    $myArray = array(
      array(
        'site_id'  => 'S6407', 
        'tssr_id'  => 'TSSRBOQ-200204-0145-59'
      ),
      array(
        'site_id'  => 'S5910', 
        'tssr_id'  => 'TSSRBOQ-200204-0145-8'
      ),
    );

    // $items_tssr is get from another variable
    foreach ($items_tssr as $key => $value) {
      $array_validate[] = array(
        'site_id' => $value['site_id'],
        'tssr_id' => $value['no_tssr_boq_site']
      );
    }

    $result = array_map('unserialize',
              array_intersect(
                  array_map('serialize', $myArray), array_map('serialize', $array_validate)));
    // if there are same 
    if(array_key_exists(0,$result)){
      echo 'process this';
    }else{
      echo 'dont process this';
    }

我的问题是,原来的$myArray多了'site_id'和'tssr_id'

$myArray_origin = array(
          'site_id' => 'S6407',
          'tssr_id'  => 'TSSRBOQ-200204-0145-59'
          'site_name' => 'Site S6407',
          'id_site_doc'=> '127361,
          'implementation_id' => 'imp4121',
          'status' => "implementation_created",
          "endstate" => false
   ),
...

我如何处理 $myArray_origin 而不丢弃一些值?因为 $array_validate 只有 2 个值 'site_id' 和 'tssr_id'

您可以改用 array_filter + in_array。这只会保留 site_idtssr_id 出现在 array_validate 自己的条目之一中的条目:

$result = array_filter($myArray, function (array $entry) use ($array_validate): bool {
  return in_array([
    'site_id' => $entry['site_id'], 
    'tssr_id' => $entry['tssr_id']
  ], $array_validate, true);
});

演示:https://3v4l.org/4Qhmr