The simplest way is to use PHP's built-in function array_flip to achieve the deduplication effect. Another method is to use PHP's array_flip function to indirectly achieve the deduplication effect.
array_flip is a function that reverses the keys and values of the array. It has a characteristic that if two values in the array are the same, then the last key and
will be retained after inversion.
value. Taking advantage of this feature, we use it to indirectly implement deduplication of arrays.
The code is as follows
代码如下 |
复制代码 |
$arr = array("a"=>"a1","b"=>'b1',"c"=>"a2","d"=>"a1");
$arr1 = array_flip($arr);
print_r($arr1);//先反转一次,去掉重复值,输出Array ( [a1] => d [b1] => b [a2] => c )
$arr2 = array_flip($arr);
print_r($arr2);//再反转回来,得到去重后的数组,输出Array ( [a1] => d [b1] => b [a2] => c )
$arr3 = array_unique($arr);
print_r($arr3);//利用php的array_unique函数去重,输出Array ( [a] => a1 [b] => b1 [c] => a2 )
?>
|
|
Copy code
|
代码如下 |
复制代码 |
function assoc_unique($arr, $key) {
$tmp_arr = array();
foreach($arr as $k => $v) {
if(in_array($v[$key], $tmp_arr)) {
unset($arr[$k]);
} else {
$tmp_arr[] = $v[$key];
}
}
sort($arr);
return $arr;
}
$aa = array(
array('id' => 123, 'name' => '淡淡清香弥漫世界'),
array('id' => 123, 'name' => '螃蟹'),
array('id' => 124, 'name' => '前端开发者'),
array('id' => 125, 'name' => '螃蟹'),
array('id' => 126, 'name' => 'HTML5研究者')
);
$key = 'name';
assoc_unique(&$aa, $key);
print_r($aa);
?>
|
$arr = array("a"=>"a1","b"=>'b1',"c"=>"a2","d"=>"a1");
$arr1 = array_flip($arr);
print_r($arr1);//Reverse it first, remove duplicate values, and output Array ([a1] => d [b1] => b [a2] => c )
$arr2 = array_flip($arr);
print_r($arr2);//Reverse it again to get the deduplicated array and output Array ([a1] => d [b1] => b [a2] => c )
$arr3 = array_unique($arr);
print_r($arr3);//Use PHP’s array_unique function to remove duplicates and output Array ( [a] => a1 [b] => b1 [c] => a2 )
?> |
User-defined function operation
The code is as follows
|
Copy code
function assoc_unique($arr, $key) {
$tmp_arr = array();
foreach($arr as $k => $v) {
if(in_array($v[$key], $tmp_arr)) {
Unset($arr[$k]);
} else {
$tmp_arr[] = $v[$key];
}
}
sort($arr);
return $arr;
}
$aa = array(
array('id' => 123, 'name' => 'A light fragrance fills the world'),
array('id' => 123, 'name' => 'crab'),
array('id' => 124, 'name' => 'Front-end developer'),
array('id' => 125, 'name' => 'crab'),
array('id' => 126, 'name' => 'HTML5 researcher')
);
$key = 'name';
assoc_unique(&$aa, $key);
print_r($aa);
?>
http://www.bkjia.com/PHPjc/632147.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632147.htmlTechArticleThe simplest way is to use the function that comes with php to use array_flip to achieve the duplication effect. Another way is to use php. The array_flip function indirectly achieves the deduplication effect array_flip is to reverse the array keys and values...
|
|