php数组求差集问题

Mark
  • 24

最近在写一个项目 项目中 涉及到数组差集问题 代码如下

<?php

$arr1 = [
    [
        "cardId" => 1010284722,
        "beforeAmounts" => 100,
        "afterAmounts" => 20,
        "diffAmounts" => -80,
        "diffStatus" => 1
    ],
    [
        "cardId" => 1010284722,
        "beforeAmounts" => 100,
        "afterAmounts" => 200,
        "diffAmounts" => 100,
        "diffStatus" => 0
    ],
    [
        "cardId" => 177561410,
        "beforeAmounts" => 2000,
        "afterAmounts" => 1000,
        "diffAmounts" => -1000,
        "diffStatus" => 1
    ],
    [
        "cardId" => 177561410,
        "beforeAmounts" => 2000,
        "afterAmounts" => 1000,
        "diffAmounts" => -1000,
        "diffStatus" => 1
    ],
    [
        "cardId" => 1077060068,
        "beforeAmounts" => 789,
        "afterAmounts" => 100,
        "diffAmounts" => -689,
        "diffStatus" => 1
    ],
    [
        "cardId" => 1077060068,
        "beforeAmounts" => 789,
        "afterAmounts" => 100,
        "diffAmounts" => -689,
        "diffStatus" => 1
    ]
];

$arr2 = [
    [
        "cardId" => 177561410,
        "beforeAmounts" => 2000,
        "afterAmounts" => 1000,
        "diffAmounts" => -1000,
        "diffStatus" => 1
    ],
    [
        "cardId" => 1077060068,
        "beforeAmounts" => 789,
        "afterAmounts" => 100,
        "diffAmounts" => -689,
        "diffStatus" => 1
    ]
];

echo 'arr1个数:'.count($arr1).'<br /><br />';
echo 'arr1集合: ';
var_dump($arr1);
echo '<hr />';

echo 'arr2个数:'.count($arr2).'<br /><br />';
echo 'arr2集合: ';
var_dump($arr2);
echo '<hr />';

//这是我求差集的方法
foreach($arr1 as $k=>$v) if(in_array($v, $arr2)) unset($arr1[$k]);

echo '差集个数:'.count($arr1).'<br /><br />';
echo '差集集合:';
var_dump($arr1);

因为有重复的数据 这样求出来之后 差集的个数 + $arr2 的个数 不等于 $arr1 的个数

问 : 怎么样求差集才能  
 差集的个数 + $arr2 的个数 = $arr1 的个数  
 而且最后求出的差集 集合也包含那两个重复的数组元素 "cardId" => 177561410 和 "cardId" => 1077060068
回复
阅读 1.6k
2 个回答
✓ 已被采纳

如果是按需求(不是差集)来实现,可以将in_array换成array_search,如果查找成功,该函数会返回命中的key,如果在arr2中能找到,在删除$arr1[$k]时,同时删除$arr2[$idx]就行了,如果要保留$arr2,就copy一个数组来操作
foreach($arr1 as $k=>$v){

$idx = array_search($v,$arr2);
if($idx !== false){ //找到了
    unset($arr1[$k]);
    unset($arr2[$idx]);
}

}

楼主1对于2的差集,就是1中不包含2的部分。不包含2的只有两个,这就是差集。如果说你需要查处的差集大于2,那和差集概念不符,也就不是差集的范畴了

你知道吗?

宣传栏