我该如何比较两个数组?

时间:2016-12-29 07:55:06

标签: php arrays compare

如何在php中比较两个数组?

    $arr1[0] = ['user_id' => 1, 'username' => 'bob'];
    $arr1[1] = ['user_id' => 2, 'username' => 'tom'];
    //and
    $arr2[0] = ['user_id' => 2, 'username' => 'tom'];
    $arr2[1] = ['user_id' => 3, 'username' => 'john'];
    $arr2[2] = ['user_id' => 21, 'username' => 'taisha'];
    $arr2[3] = ['user_id' => 1, 'username' => 'bob'];

我需要返回不包含双倍的数组:

$result[0] = ['user_id' => 3, 'username' => 'john'];
$result[1] = ['user_id' => 21, 'username' => 'taisha'];

3 个答案:

答案 0 :(得分:2)

我会做嵌套的foreach循环

$tmpArray = array();

foreach($newData as $arr2) {

  $duplicate = false;
  foreach($oldData as $arr1) {
    if($arr1['user_id'] === $arr2['user_id'] && $arr1['username'] === $arr2['username']) $duplicate = true;
  }

  if($duplicate === false) $tmpArray[] = $arr2;
}

然后你可以使用$ tmpArray作为newArray

答案 1 :(得分:0)

我为你的问题做了一个功能

function compareArrays($array1,$array2)
{
    $merged_array = array_merge($array1,$array2);
    $trimmed_array=[];
    foreach($merged_array as $array)
    {
        $found=false;
        $index_flag;
        foreach($trimmed_array as $key=>$tarr)
        {
            if($tarr['user_id']==$array['user_id'] && $tarr['username']==$array['username'] )
            {
                $found=true;
                $index_flag=$key;
                break;
            }
        }
        if($found)
        {
            array_splice($trimmed_array, $index_flag,1);
        }
        else
        {
            array_push($trimmed_array,$array);
        }
    }
    return $trimmed_array;
}

我对它进行了测试并得到了完全属于您的结果,您可以使用像

这样的数组来调用它
   compareArrays($arr1,$arr2);

答案 2 :(得分:0)

您可以使用标准功能来实现目标:

// Function that sorts element array by key and
// kinda create string representation (needed for comparing).
$sortByKeyAndSerialize = function (array $item) {
    ksort($item);

    return serialize($item);
};

// Map arrays to arrays of string representation and leave only unique.
$arr1 = array_unique(array_map($sortByKeyAndSerialize, $arr1));
$arr2 = array_unique(array_map($sortByKeyAndSerialize, $arr2));

// Merge two arrays together and count values 
// (values become keys and the number of occurances become values).
$counts = array_count_values(array_merge($arr1, $arr2));

// Leave only elements with value of 1
// (i.e. occured only once).
$unique = array_filter($counts, function ($item) {
    return $item === 1;
});

// Grab keys and unserialize them to get initial values.
$result = array_map('unserialize', array_keys($unique));

这是working demo

随意将此代码包装在函数或其他任何内容中。

避免在代码中使用嵌套循环,这是一个糟糕的伏都教。如果可能,请避免使用显式循环(例如forwhile)。