Home  >  Article  >  Backend Development  >  Detailed explanation of php function to remove duplicate elements from array and sort by key name

Detailed explanation of php function to remove duplicate elements from array and sort by key name

怪我咯
怪我咯Original
2017-07-05 10:40:441394browse

Use PHP to remove duplicate elements in array function

1. The function of this function: remove duplicate elements from 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' => '张三'), 
array('id' => 123, 'name' => '李四'), 
array('id' => 124, 'name' => '王五'), 
array('id' => 125, 'name' => '赵六'), 
array('id' => 126, 'name' => '赵六') 
); 
$key = 'id'; 
assoc_unique(&$aa, $key); 
print_r($aa);

The above is the detailed content of Detailed explanation of php function to remove duplicate elements from array and sort by key name. For more information, please follow other related articles on the PHP Chinese website!

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