本文介绍了比较两个数组以使用PHP函数查找差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using PHP in magento2, I need to compare two arrays. $Session array size will be larger than $post array size. So I need to compare my $post values with $session values. If both arrays have same values for all the keys, then empty array should be returned.

$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;
}

我不知道缺少什么.请帮忙!谢谢

I don't know what am missing. Please help! Thank you

推荐答案

来自此问题:

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

这篇关于比较两个数组以使用PHP函数查找差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 06:20