Php array de-duplicates array elements. The simplest method is to use the built-in functions of php to implement de-duplication with array_flip, another method is to use the array_flip function of php to indirectly implement de-duplication. array_flip is the easiest way to reverse the array key and value. The built-in function of php uses array_flip to achieve de-duplication, another method is to use the array_flip function of php to indirectly implement deduplication.
Array_flip is a function that reverses the array key and value. it has a feature that if two values in the array are the same, the last key and value will be retained after the inversion.
Value. We use this feature to indirectly implement array deduplication.
| The code is as follows: |
|
$ Arr = array ("a" => "a1", "B" => 'b1 ', "c" => "a2 ", "d" => "a1 "); $ Arr1 = array_flip ($ arr ); Print_r ($ arr1); // first reverse the expression, remove the duplicate value, and output Array ([a1] => d [b1] => B [a2] => c) $ Arr2 = array_flip ($ arr ); Print_r ($ arr2); // returns the array after deduplication, output Array ([a1] => d [b1] => B [a2] => c) $ Arr3 = array_unique ($ arr ); Print_r ($ arr3); // use the array_unique function of php to deduplicate and output Array ([a] => a1 [B] => b1 [c] => a2) ?> |
User-defined function operations
| The code is as follows: |
|
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; } $ Aa = array ( Array ('id' => 123, 'name' => 'faint fragrance filled the world '), Array ('id' => 123, 'name' => 'crab '), Array ('id' => 124, 'name' => 'front-end developer '), Array ('id' => 125, 'name' => 'crab '), Array ('id' => 126, 'name' => 'html5 investigator ') ); $ Key = 'name '; Assoc_unique (& $ aa, $ key ); Print_r ($ aa ); ?> |
Array_flip is used to reverse the array key and value...