-
-
/** - * Remove duplicate data from array
- * by bbs.it-home.org
- **/
- $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’s own array_unique function only applies to one-dimensional arrays, not multi-dimensional arrays Applicable, here is a PHP two-dimensional array deduplication array_unique function.
Example:
-
- /**
- * PHP two-dimensional array to remove duplicate data
- * by bbs.it-home.org
- */
- function unique_arr($array2D,$stkeep=false,$ndformat=true)
- {
- // Determine whether to retain the first-level array key (one Level 2 array keys can be non-numeric)
- if($stkeep) $stArr = array_keys($array2D);
- // Determine whether to keep level 2 array keys (all level 2 array keys must be the same)
- if($ndformat) $ndArr = array_keys(end($array2D));
- //For 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);
- //Remove the The opened array is reassembled
- 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
Call example:
-
- //Array deduplication
- $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
|