Home > Backend Development > PHP Tutorial > Sorting function PHP removes duplicate elements from an array and sorts by key

Sorting function PHP removes duplicate elements from an array and sorts by key

WBOY
Release: 2016-07-29 08:38:33
Original
1112 people have browsed it

1. The role 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' => 'Zhang San'),
array( 'id' => 123, 'name' => '李思'),
array('id' => 124, 'name' => '王五'),
array('id' = > 125, 'name' => 'Zhao Liu'),
array('id' => 126, 'name' => 'Zhao Liu')
);
$key = 'id';
assoc_unique(&$aa, $key);
print_r($aa);

The above introduces the sorting function PHP function to remove duplicate elements in the array and sort by key name, including the sorting function. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template