One-dimensional array
$aa=array("apple","banana","pear","apple","wail","watermalon");
$bb=array_unique($aa);
print_r($bb);//Array ( [0] => apple [1] => banana [2] => pear [4] => wail [5] => watermalon
Two-dimensional array
1) Because the value of a certain key name cannot be repeated, delete duplicates
$aa = array(
array('id' => 123, 'name' => '张三'),
array('id' => 123, 'name' => '李四'),
array('id' => 124, 'name' => '王五'),
array('id' => 125, 'name' => '赵六'),
array('id' => 126, 'name' => '赵六')
);
//需求,id 不能重复functionassoc_unique($arr, $key){$tmp_arr = array();
foreach($arras$k => $v){
//搜索$v[$key]是否在$tmp_arr数组中存在,若存在返回trueif(in_array($v[$key], $tmp_arr)){
unset($arr[$k]);
}else {
$tmp_arr[] = $v[$key];
}
}
sort($arr); //sort函数对数组进行排序return$arr;
}
$key = 'id';
assoc_unique(&$aa, $key);
print_r($aa);
//Array ( [0] => Array ( [id] => 123 [name] => 张三 ) [1] => Array ( [id] => 124 [name] => 王五 ) [2] => Array ( [id] => 125 [name] => 赵六 ) [3] => Array ( [id] => 126 [name] => 赵六 ) )
2) Because the internal one-dimensional array cannot be exactly the same, delete duplicates
$aa = array(
array('id' => 123, 'name' => '张三'),
array('id' => 123, 'name' => '李四'),
array('id' => 124, 'name' => '王五'),
array('id' => 123, 'name' => '李四'),
array('id' => 126, 'name' => '赵六')
);
functionarray_unique_fb($array2D){foreach ($array2Das$v){
$v = join(",",$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串$temp[] = $v;
}
$temp = array_unique($temp); //去掉重复的字符串,也就是重复的一维数组foreach ($tempas$k => $v){
$temp[$k] = explode(",",$v); //再将拆开的数组重新组装
}
return$temp;
}
$bb=array_unique_fb($aa);
print_r($bb);
//Array ( [0] => Array ( [0] => 123 [1] => 张三 ) [1] => Array ( [0] => 123 [1] => 李四 ) [2] => Array ( [0] => 124 [1] => 王五 ) [4] => Array ( [0] => 126 [1] => 赵六 ) )
Copyright Statement: Knowledge comes from the people and is used by the people! Reprinting is welcome. Please attach a link to this article at the beginning. The article will be updated from time to time!
The above introduces PHP array deduplication, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.