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: |
Copy code |
<? Php $ 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: |
Copy code |
<? Php 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 ); ?> |