- $ Aa = array ("apple", "banana", "pear", "apple", "wail", "watermalon ");
- $ Bb = array_unique ($ aa );
- Print_r ($ bb );
- ?>
Output result: Array ([0] => apple [1] => banana [2] => pear [4] => wail [5] => watermalon ). 2. duplicate items of two-dimensional PHP arrays: We will discuss two types of two-dimensional arrays. one is because the values of one-click names cannot be repeated and repeated items are deleted; in addition, duplicate items are deleted because the internal one-dimensional arrays cannot be identical. Example 1: delete duplicate items because the values of one-click names cannot be repeated. Code:
- Function assoc_unique ($ arr, $ key)
- {
- $ Tmp_arr = array ();
- Foreach ($ arr as $ k => $ v)
- {
- If (in_array ($ v [$ key], $ tmp_arr) // search for $ v [$ key] in the $ tmp_arr array. if yes, true is returned.
- // Bbs.it-home.org
- Unset ($ arr [$ k]);
- }
- Else {
- $ Tmp_arr [] = $ v [$ key];
- }
- }
- Sort ($ arr); // sort the array
- Return $ arr;
- }
- $ Aa = array (
- Array ('id' => 123, 'name' => 'Zhang San '),
- Array ('id' => 123, 'name' => 'Lily '),
- Array ('id' => 124, 'name' => 'Wang Wu '),
- Array ('id' => 125, 'name' => 'Zhao Liu '),
- Array ('id' => 126, 'name' => 'Zhao Liu ')
- );
- $ Key = 'id ';
- Assoc_unique (& $ aa, $ key );
- Print_r ($ aa );
- ?>
-
Output result: Array ([0] => Array ([id] => 123 [name] => Zhang San) [1] => Array ([id] => 124 [name] => Wang Wu) [2] => Array ([id] => 125 [name] => Zhao 6) [3] => Array ([id] => 126 [name] => Zhao 6) Example 2: duplicate items are deleted because the internal one-dimensional arrays cannot be identical. Code:
- Function array_unique_fb ($ array2D ){
- Foreach ($ array2D as $ v ){
- $ V = join (",", $ v); // dimension reduction. you can also use implode to convert a one-dimensional array to a string connected with commas (,).
- $ Temp [] = $ v;
- } // Bbs.it-home.org
- $ Temp = array_unique ($ temp); // remove the duplicate string, that is, the duplicate one-dimensional array.
- Foreach ($ temp as $ k => $ v ){
- $ Temp [$ k] = explode (",", $ v); // re-assemble the split array
- }
- Return $ temp;
- }
- $ Aa = array (
- Array ('id' => 123, 'name' => 'Zhang San '),
- Array ('id' => 123, 'name' => 'Lily '),
- Array ('id' => 124, 'name' => 'Wang Wu '),
- Array ('id' => 123, 'name' => 'Lily '),
- Array ('id' => 126, 'name' => 'Zhao Liu ')
- );
- $ Bb = array_unique_fb ($ aa );
- Print_r ($ bb)
- ?>
Output result: Array ([0] => Array ([0] => 123 [1] => Zhang San) [1] => Array ([0] => 123 [1] => Li Si) [2] => Array ([0] => 124 [1] => Wang Wu) [4] => Array ([0] => 126 [1] => Zhao 6 )) |