比较2个数组的差异,重复一些值

时间:2017-06-07 07:30:43

标签: php arrays excel

我有两个要比较的数组,我使用array_diff来计算列的差异,如下所示:

//array1 is as static array I have created to validate the sheet columns
$array1 = array('Category','Subcategory','Unknown','Age','0-9','Unknown','Region','Zone'); 

// array2 is coming dynamically from excel sheet columns so user can change the names
$array2 = array('Category','Subcategory','Unknowns','Age','0-9','Unknown','Region'); 

$diff = array_diff($array1,$array2);
$columnNames = implode(',',$diff);
if(!$diff){
   return true;
}
else{
  echo 'Some columns are missing:'. $columnNames ;
}

输出 Zone

预期输出: Zone, Unknowns

如果Unknown列未更改,则上述代码可以正常工作。我知道array_diff只会检查第一个数组并比较下一个数组中的值。但是,我想比较这些数组并向用户显示一些消失的消息及其名称。因此,如果其中一列已在excel表格中更改为Unknowns,例如array2,则应显示错误消息Some columns are missing: Zone, Unknowns

3 个答案:

答案 0 :(得分:2)

试试此代码

array_merge(array_diff($array1,$array2),array_diff($array2,$array1))

参考:https://stackoverflow.com/a/16356205/4895810

答案 1 :(得分:2)

您可以从两个数组的并集中包含两个数组的交集。的 Live Demo

$array = array_diff(array_merge($array1, $array2), array_intersect($array1, $array2));

答案 2 :(得分:1)

在PHP中使用array_diff_assoc函数试试这个:

     //array1 is as static array I have created to validate the sheet columns
 $array1 = array('Category','Subcategory','Unknown','Age','0-9','Unknown','Region','Zone'); 

 // array2 is coming dynamically from excel sheet columns so user can change the names
 $array2 = array('Category','Subcategory','Unknowns','Age','0-9','Unknown','Region'); 

 $diff = array_diff_assoc($array1,$array2);
 $columnNames = implode(',',$diff);

 echo $columnNames;

如需参考,请访问此网站http://php.net/manual/en/function.array-diff-assoc.php