Php array deduplication of array elements

Source: Internet
Author: User

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 );
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.