使用PHP函数比较两个数组以找到差异

时间:2018-05-22 02:36:57

标签: php php-7

在magento2中使用PHP,我需要比较两个数组。 $ Session 数组大小将大于 $ post 数组大小。所以我需要将$ post值与$ session值进行比较。如果两个数组的所有键都具有相同的值,则应返回空数组。

$session = [
    "domains" => 'x',
    "domain" => '',
    "searchfilter" => 'AD DOmain',
    "searchterm" => ''
];
$post = [
    "domains" => 'xx',
    "domain" => 'AD DOmain',
    "searchfilter" => ''
];
$result = $this->formArray($post, $session) ;

我的预期结果:

Array()
{
  "domains" => 'xx',
  "domain" => 'AD DOmain',
  "searchfilter" => ''
}

我的实际结果:

Array()
{
}

我尝试了类似的事情,

public function formArray($post, $session){
        $checkNewValue = array_diff($post, $session);
        $checkNewKey = array_diff_key($post, $session);
        $mergedArray = array_merge($checkNewValue, $checkNewKey);
        return $mergedArray;
}

我不知道遗失了什么。请帮忙!谢谢

3 个答案:

答案 0 :(得分:2)

从这个问题:PHP - Merging two arrays into one array (also Remove Duplicates)

$session = [
    "domains" => 'x',
    "domain" => '',
    "searchfilter" => 'AD DOmain',
    "searchterm" => ''
];
$post = [
    "domains" => 'xx',
    "domain" => 'AD DOmain',
    "searchfilter" => ''
];
//This will return true if both `$session` and `$post` has the same key/value pair. 

http://www.php.net/manual/en/language.operators.array.php

`$a == $b   Equality    TRUE if $a and $b have the same key/value pairs.`

if($session == $post){
     $new_arr = array();
}else{
     $new_arr = array_unique(array_merge($session,$post), SORT_REGULAR);    
}

echo '<pre>';
print_r($new_arr);

结果:

//if array are not equal

Array
(
    [domains] => xx
    [domain] => AD DOmain
    [searchfilter] => 
)

  //else
   Array()

答案 1 :(得分:1)

array_diff_assoc可以在这里使用。

  

array_diff_assoc - 计算数组的差异   额外的索引检查

答案 2 :(得分:1)

尝试使用array_diff_assoc。

<?php
$session = [
    "domains" => 'x',
    "domain" => '',
    "searchfilter" => 'AD DOmain',
    "searchterm" => ''
];
$post = [
    "domains" => 'xx',
    "domain" => 'AD DOmain',
    "searchfilter" => ''
];

$checkNewValue = array_diff_assoc($post, $session);
var_dump($checkNewValue);

?>