从关联数组中获取不同的值

时间:2017-12-25 09:37:10

标签: php arrays

我有两个关联数组,如下所示:

$array1 = array("field1"=>1,"field2"=>1,"field3"=>1,"field4"=>1,"field5"=>1);

$array2 = array("field1"=>1,"field2"=>0,"field3"=>1,"field4"=>0,"field5"=>1);

现在我想合并并找到不同的值。

我尝试了array_intersect

$result =  array_intersect($array1,$array2) ;

但它返回以下输出:

Array
(
    [field1] => 1
    [field2] => 1
    [field3] => 1
    [field4] => 1
    [field5] => 1
)

我需要输出

Array
(
    [field2] => 1
    [field4] => 1
)

我如何实现这一目标?

2 个答案:

答案 0 :(得分:4)

尝试array_diff_assoc

它使用额外的索引检查来计算数组的差异。

$array1 = array("field1"=>1,"field2"=>1,"field3"=>1,"field4"=>1,"field5"=>1);

$array2 = array("field1"=>1,"field2"=>0,"field3"=>1,"field4"=>0,"field5"=>1);

$result =  array_diff_assoc($array1,$array2) ;

echo "<pre>";
print_r($result);

现场演示:https://eval.in/924926

答案 1 :(得分:0)

很简单。你必须寻找 array_diff_assoc()函数。

 How it Works :- Returns an array containing all the values from array1 that are 
            not present in any of the other arrays (in your case $array2).
$array1 = array("field1"=>1,"field2"=>1,"field3"=>1,"field4"=>1,"field5"=>1);
$array2 = array("field1"=>1,"field2"=>0,"field3"=>1,"field4"=>0,"field5"=>1);
$output =  array_diff_assoc($array1,$array2) ;
var_dump($output);

希望它有所帮助!