当前位置:Gxlcms > PHP教程 > 求这个两个数组的差集?

求这个两个数组的差集?

时间:2021-07-01 10:21:17 帮助过:23人阅读

Array ( [0] => Array ( [id] => 11 [parametername] => 参数名称11 ) )

Array ( [0] => Array ( [id] => 6 [parametername] => 参数名称6 ) [1] => Array ( [id] => 10 [parametername] => 参数名称10 ) [2] => Array ( [id] => 11 [parametername] => 参数名称11 ) [3] => Array ( [id] => 15 [parametername] => 参数编辑 ) [4] => Array ( [id] => 16 [parametername] => 参数20 ) )

回复内容:

Array ( [0] => Array ( [id] => 11 [parametername] => 参数名称11 ) )

Array ( [0] => Array ( [id] => 6 [parametername] => 参数名称6 ) [1] => Array ( [id] => 10 [parametername] => 参数名称10 ) [2] => Array ( [id] => 11 [parametername] => 参数名称11 ) [3] => Array ( [id] => 15 [parametername] => 参数编辑 ) [4] => Array ( [id] => 16 [parametername] => 参数20 ) )

$array1 = array(
    array('n3'=>'v3', 'n4'=>'v4'),
    array('n1'=>'v1', 'n2'=>'v2')
);

$array2 = array(
    array('n1'=>'v1', 'n2'=>'v2')
);

$result = array_udiff(
    $array1,
    $array2,
    function ($v1, $v2) {
        return strcmp(serialize($v1), serialize($v2));
    }
)

// 或者

$result = array_filter($array1, function($v) use ($array2) {
    return in_array($v, $array2);
});

你可以试试。

回调是你的好朋友。

数据:

 11, "parametername" => "PARAMETER NAME XI" ) , 
    array( "id" => 30, "parametername" => "PARAMETER NAME XXX" ) , 
);
$array2 = array(
    array( "id" => 6, "parametername" => "Parameter Name VI" ), 
    array( "id" => 10, "parametername" => "Parameter Name X" ) , 
    array( "id" => 11, "parametername" => "Parameter Name XI" ) , 
    array( "id" => 15, "parametername" => "Parameter Name XV" ) , 
    array( "id" => 16, "parametername" => "Parameter Name XVI" ) , 
);

比较代码如下:

array_udiff($array2, $array1, function($a, $b) {
    return ($a['id'] - $b['id']);
});
/*
array(
    array( "id" => 6, "parametername" => "Parameter Name VI" ), 
    array( "id" => 10, "parametername" => "Parameter Name X" ) , 
    array( "id" => 15, "parametername" => "Parameter Name XV" ) , 
    array( "id" => 16, "parametername" => "Parameter Name XVI" ) , 
)
*/

array_udiff($array1, $array2, function($a, $b) {
    return ($a['id'] - $b['id']);
})
/*
array(
    array( "id" => 30, "parametername" => "PARAMETER NAME XXX" ), 
)
*/

另外我希望没理解错题意。以上代码均认为只要id相同就属于同一个数据。如果有必要自行更改回调的逻辑。

回调很好。。学了一招。

人气教程排行