-
- if (count($array) != count(array_unique($array))) {
- echo 'The array has duplicate values';
- }
- ?>
Copy code
PHP remove duplicate array data
-
-
$input = array("a" => "green","", "red","b" => "green", "" ,"blue", "red","c" => "witer","hello","witer");
- //$result = array_unique($input); //Remove duplicate elements
- $result = a_array_unique ($input); //Leave only a single element
- foreach($result as $aa)
- {
- echo $aa."
";
- }
- function multi_unique($array) {
- foreach ( $array as $k=>$na)
- $new[$k] = serialize($na);
- $uniq = array_unique($new);
- foreach($uniq as $k=>$ser)
- $new1[$k] = unserialize($ser);
- return ($new1);
- }
function a_array_unique($array)//Written better
- {
- $out = array();
- foreach ($array as $key=>$value) {
- if (!in_array($value, $out))
- {
- $out[$key] = $value;
- }
- }
- return $out;
- }
- ?>
-
-
Copy code
PHP array has a built-in function array_unique () to remove duplicate items, but PHP's array_unique function only applies to one-dimensional arrays. Not suitable for multi-dimensional arrays.
The following implements the array_unique function of a two-dimensional array:
-
- function unique_arr($array2D,$stkeep=false,$ndformat=true)
- {
- // Determine whether to retain the first-level array key (the first-level array key can be non-numeric)
- if($stkeep) $stArr = array_keys($array2D);
- // Determine whether to retain the secondary array keys (all secondary array keys must be the same)
- if($ndformat) $ndArr = array_keys(end($array2D)) ;
- //Dimensionality reduction, you can also use implode to convert a one-dimensional array into a string connected with commas
- foreach ($array2D as $v){
- $v = join(",",$v);
- $ temp[] = $v;
- }
- //Remove repeated strings, that is, repeated one-dimensional arrays
- $temp = array_unique($temp);
- //Reassemble the disassembled array
- foreach ($ temp as $k => $v)
- {
- if($stkeep) $k = $stArr[$k];
- if($ndformat)
- {
- $tempArr = explode(",",$v);
- foreach($tempArr as $ndkey => $ndval) $output[$k][$ndArr[$ndkey]] = $ndval;
- }
- else $output[$k] = explode(",",$ v);
- }
- return $output;
- }
- ?>
-
Copy code
Test case:
-
- $array2D = array('first'=>array('title'=>'1111','date'=>'2222'),'second'=> ;array('title'=>'1111','date'=>'2222'),'third'=>array('title'=>'2222','date'=>'3333 '));
- print_r($array2D);
- print_r(unique_arr($array2D,true));
- ?>
Copy code
php determines whether the same value exists in the array array_unique 1 2 times One last page
|