Home >Backend Development >PHP Tutorial >PHP function to remove duplicate elements from an array and sort by key_PHP tutorial

PHP function to remove duplicate elements from an array and sort by key_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:50:49831browse

1. The role of this function: remove duplicate elements in the array and sort by key name
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;
}

Usage example:
$aa = array(
array('id' => 123, 'name' => 'Zhang San'),
array('id' => 123, 'name' => ' Li Si'),
array('id' => 124, 'name' => 'Wang Wu'),
array('id' => 125, 'name' => ' Zhao Liu'),
array('id' => 126, 'name' => 'Zhao Liu')
);
$key = 'id';
assoc_unique(& $aa, $key);
print_r($aa);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/319293.htmlTechArticle1. The function of this function: remove duplicate elements in the array and sort by key name function assoc_unique($arr, $ key) { $tmp_arr = array(); foreach($arr as $k = $v) { if(in_array($v[$key], $t...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn