/**
* 以第一個(gè)參數(shù)為主進(jìn)行進(jìn)行比較
* **/
function diffArray($arr1 , $arr2 ){
$arrRet = array();
#針對(duì)關(guān)聯(lián)數(shù)組
if(is_assoc($arr1) && is_assoc($arr2) ){
if (empty($arr1)) {
$arr1 = array();
}
if (empty($arr2)) {
$arr2 = array();
}
foreach ($arr1 as $key => $value){
if(!in_array($key, array_keys($arr2))){
if(!array_key_exists($key, $arrRet)){
array_push($arrRet, $key);
}
continue;
}
if($arr1[$key] !== $arr2[$key]){
if(!array_key_exists($key, $arrRet)){
array_push($arrRet, $key);
}
}
#針對(duì)元素為數(shù)組的情況
if(is_array($value)){
array_merge($arrRet,diffArray($value,$arr2[$key]));
}
}
}elseif(is_assoc($arr1)===false && is_assoc($arr2)===false) {#針對(duì)索引數(shù)組
$arrRet = array_merge(array_diff($arr1, $arr2),array_diff($arr2, $arr1));
}else {
new Exception("數(shù)組類(lèi)型不一致!");
}
return $arrRet;
}
/**
* 判斷是否為關(guān)聯(lián)數(shù)組
* **/
function is_assoc($arr) {
if(!is_array($arr)) return -1;
return !(array_values($arr) === $arr);
}
$arr1 = array(
//"channelNameShort"=> "百度時(shí)代公司",
//"channelName"=>"百度時(shí)代責(zé)任有限公司",
"rawUrl"=>"http://www.baidu.com",
"logoUrl"=> "http://t11.baidu.com/it/u=3114404026,3614407463&fm=58",
"channelType"=> array(
"210010004",
"210010007",
),
"mobileURL" => "http://www.bb.com",
"rockArray" => array(
"A" => 1,
"B" => array(1,2,3),
),
//"null" => array(),
);
$arr2 = array(
//"channelNameShort"=> "百度時(shí)代公司",
//"channelName"=>"百度在線公司",
"rawUrl"=>"http://www.baidu.com",
"logoUrl"=> "http://t11.baidu.com/it/u=3114404026,3614407463&fm=58",
"mobileURL" => "",
"rockArray" => array(
"A" => 1,
"B" => 2,
),
"channelType"=> array(
"210010004",
"210010017",
),
"null" => array(),
);
/*$arr3 = array(
1,2,3,4
);
var_dump(is_assoc($arr1))*/
/*$arr1 = array(1,3,5,7,9);
$arr2 = array(1,2,5,6,9);*/
var_dump(diffArray($arr1, $arr2));
var_dump(array_unique(array_merge(diffArray($arr1, $arr2),diffArray($arr2, $arr1))));
本文標(biāo)題:PHP對(duì)比兩個(gè)數(shù)據(jù)中不同的元素
分享鏈接:
http://weahome.cn/article/jedopo.html