看到你,梁松远的博客

位置 » 主页 » 代码分享 » 提取重复数组,并且返回去除重复的就数组和重复的数组

提取重复数组,并且返回去除重复的就数组和重复的数组

 <?php

//提取重复数组,并且返回去除重复的就数组和重复的数组
function assoc_unique($array, $uname)
{
foreach($array as $key => $val){//删掉指定的减值,并生成一个新的一维数组,值是二维数组第二维的json值
unset($val[$uname]);
$newarray[$key] = json_encode($val);
}
$arr_id = array();//声明一个空数组,后面用到
foreach($newarray as $k => $v){//循环新数组,
foreach($newarray as $ka => $va){//再次循环新数组,目的是与第一次循环的键名做对比,如果相同,则跳过,如果不同,则按指定格式保存键名成二维数组
if($k == $ka){
continue;
}
if($v == $va){
$arr_id[$k][] = $ka;
$arr_id[$k][] = $k;
}
}
}
foreach($arr_id as $key=> $val){//循环只有键名的数组,并且对其去重,排序,最后又生成一个新的一维数组。
$nid = array_unique($val);
sort($nid);
$arr_id2[$key] = json_encode($nid);
}
$arr_id2 = array_unique($arr_id2);//对新数组进行去重,
foreach($arr_id2 as $key => $val){//对新数组进行json解码
$arr_id2[$key] = json_decode($val);
}
if($arr_id2){//如果存在则,
foreach($arr_id2 as $k=> $v){//由于是二维数组,所以循环第二次才得到值
foreach($v as $kk => $vv){//这是第二次循环
$arr2[$k][] = $array[$vv];//根据相同的值中再做不同分类。
unset($array[$vv]);//上面已经有了,所以这里就unset了
}
}
}
return array($arr2,$array);
}
$array = array(
array('aa'=>1111,'bb'=>1231,'cc'=>3333),
array('aa'=>1111,'bb'=>2222,'cc'=>456),
array('aa'=>1111,'bb'=>2222,'cc'=>123),
array('aa'=>2234,'bb'=>2222,'cc'=>45677),
array('aa'=>4564,'bb'=>2222,'cc'=>3333),
array('aa'=>2234,'bb'=>2222,'cc'=>3333),
);
 
$arr=array(
0  => array("xinghao" => "ADA4851-4YRUZ-RL7","pack" => "TSSOP14","year" => "2013+","brand" => "ADI","stock" => 10000,"price" => 69.1752),
1  => array("xinghao" => "PCM1794ADBR","pack" => "SSOP28","year" => "2013+","brand" => "BB","stock" => 1500,"price" => 68.7500),
2  => array("xinghao" => "ADA4851-4YRUZ-RL7","pack" => "TSSOP14","year" => "2013+","brand" => "ADI","stock" => 10000,"price" => 65.2384),
5  => array("xinghao" => "ADA4851-4YRUZ-RL7","pack" => "TSSOP14","year" => "2013+","brand" => "ADI","stock" => 10000,"price" => 64.2384),
3  => array("xinghao" => "PCM1794ADBR","pack" => "SSOP28","year" => "2013+","brand" => "BB","stock" => 1500,"price" => 63.8000),
4  => array("xinghao" => "OPA4354AIDR","pack" => "SOP14","year" => "2013+","brand" => "TI","stock" => 15000,"price" => 57.9370)
);
 
print_r(assoc_unique($arr, 'price'));
 
 
array(
'0'=>array(
array('aa'=>1111,'bb'=>2222,'cc'=>456),
array('aa'=>1111,'bb'=>2222,'cc'=>123),
),
'1'=>array(
array('aa'=>2234,'bb'=>2222,'cc'=>45677),
array('aa'=>2234,'bb'=>2222,'cc'=>3333),
),
'old'=>array(
array('aa'=>1111,'bb'=>1231,'cc'=>3333),
array('aa'=>4564,'bb'=>2222,'cc'=>3333),
)
);