- If (count ($ array )! = Count (array_unique ($ array ))){
- Echo 'This array has repeated values ';
- }
- ?>
PHP removes repeated 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); // only a single element is left.
- 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) // write better
- {
- $ Out = array ();
- Foreach ($ array as $ key => $ value ){
- If (! In_array ($ value, $ out ))
- {
- $ Out [$ key] = $ value;
- }
- }
- Return $ out;
- }
- ?>
-
PHP array deduplication has a built-in function array_unique (), but php's array_unique function is only applicable to one-dimensional arrays and not to multidimensional arrays. The array_unique function of a two-dimensional array is implemented as follows:
- Function unique_arr ($ array2D, $ stkeep = false, $ ndformat = true)
- {
- // Determine whether the primary array key is retained (the primary array key can be non-numeric)
- If ($ stkeep) $ stArr = array_keys ($ array2D );
- // Determine whether the secondary array key is retained (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 to a string connected with commas (,).
- Foreach ($ array2D as $ v ){
- $ V = join (",", $ v );
- $ Temp [] = $ v;
- }
- // Remove the duplicate string, that is, the duplicate one-dimensional array.
- $ Temp = array_unique ($ temp );
- // Re-assemble the split 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;
- }
- ?>
-
Test cases:
- $ Array2D = array ('first' => array ('title' => '123', 'date' => '123 '), 'second' => array ('title' => '123', 'date' => '123 '), 'third' => array ('title' => '123456', 'date' => '123456 '));
- Print_r ($ array2D );
- Print_r (unique_arr ($ array2D, true ));
- ?>
Php checks whether the same value array_unique exists in the array.12. Next page |