Home  >  Article  >  Backend Development  >  求这个两个数组的差集?

求这个两个数组的差集?

WBOY
WBOYOriginal
2016-06-06 20:44:091077browse

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 ) )

<code>$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);
});
</code>

你可以试试。

回调是你的好朋友。

数据:

<code><?php $array1 = array(
    array( "id" => 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" ) , 
);
</code>

比较代码如下:

<code>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" ), 
)
*/
</code>

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

回调很好。。学了一招。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn