比较两个二维数组并获取交集和差异

问题描述 投票:0回答:2

我想比较两个数组之间整行的数据并产生:

  • 相交行的数组和
  • 第一个数组中的行在第二个数组中找不到的数组,并且
  • 在第一个数组中找不到第二个数组中的行的数组。

我有两个多维数组。

$array1 = [
    ['sight_id' => 13, 'location' => 'Jodhpur, Rajasthan, India'],
    ['sight_id' => 14, 'location' => 'Jodhpur Jn, Jodhpur, Rajasthan, India'],
    ['sight_id' => 15, 'location' => 'D-Kirtinagar, Jodhpur, Rajasthan, India'],
];

$array2 = [
    ['sight_id' => 13, 'location' => 'Jodhpur, Rajasthan, India'],
    ['sight_id' => 14, 'location' => 'Jodhpur Jn, Jodhpur, Rajasthan, India'],
    ['sight_id' => 16, 'location' => 'Jaisalmer, Rajasthan, India'],
    ['sight_id' => 17, 'location' => 'Fort Road, Amar Sagar Pol, Jaisalmer, Rajasthan, India'],
];

期望的结果:

$intersect_array = [
    ['sight_id' => 13, 'location' => 'Jodhpur, Rajasthan, India'],
    ['sight_id' => 14, 'location' => 'Jodhpur Jn, Jodhpur, Rajasthan, India'],

$only_a1 = [
    ['sight_id' => 15, 'location' => 'D-Kirtinagar, Jodhpur, Rajasthan, India'],
]

$only_a2 = [
    ['sight_id' => 16, 'location' => 'Jaisalmer, Rajasthan, India'],
    ['sight_id' => 17, 'location' => 'Fort Road, Amar Sagar Pol, Jaisalmer, Rajasthan, India'],
];
php multidimensional-array filtering array-difference array-intersect
2个回答
1
投票

将数组转换为某种格式,其中数组索引是sight_id:

$b1 =array();
foreach($a1 as $x)
    $b1[$x['sight_id']] = $x['location'];

$b2 =array();
foreach($a2 as $x)
    $b2[$x['sight_id']] = $x['location'];

计算差值和交集:

$c_intersect = array_intersect_key($b1,$b2);
$c_1 = array_diff_key($b1,$b2);
$c_2 = array_diff_key($b2,$b1);

将数组转换回您的格式:

$intersect_array = array();
foreach($c_intersect as $i=>$v)
    $intersect_array[] = array('sight_id'=>$i,'location'=>$v);

$only_a1 = array();
foreach($c_1 as $i=>$v)
    $only_a1[] = array('sight_id'=>$i,'location'=>$v);

$only_a2 = array();
foreach($c_2 as $i=>$v)
    $only_a2[] = array('sight_id'=>$i,'location'=>$v);

1
投票

无需为了比较行而改变/准备二维数组。由于一个数组中的整行与另一个数组中的整行相关,因此您无需指定要比较的列 - 只需比较整行数据即可。

代码:(演示)(或使用声明的函数

echo "Intersection:\n";
var_export(
    array_uintersect($array1, $array2, fn($a, $b) => $a <=> $b)
);

echo "\nUnique in first:\n";
var_export(
    array_udiff($array1, $array2, fn($a, $b) => $a <=> $b)
);

echo "\nUnique in second:\n";
var_export(
    array_udiff($array2, $array1, fn($a, $b) => $a <=> $b)
);

输出:

Intersection:
array (
  0 => 
  array (
    'sight_id' => 13,
    'location' => 'Jodhpur, Rajasthan, India',
  ),
  1 => 
  array (
    'sight_id' => 14,
    'location' => 'Jodhpur Jn, Jodhpur, Rajasthan, India',
  ),
)
Unique in first:
array (
  2 => 
  array (
    'sight_id' => 15,
    'location' => 'D-Kirtinagar, Jodhpur, Rajasthan, India',
  ),
)
Unique in second:
array (
  2 => 
  array (
    'sight_id' => 16,
    'location' => 'Jaisalmer, Rajasthan, India',
  ),
  3 => 
  array (
    'sight_id' => 17,
    'location' => 'Fort Road, Amar Sagar Pol, Jaisalmer, Rajasthan, India',
  ),
)
© www.soinside.com 2019 - 2024. All rights reserved.