| This article introduces how to remove duplicates from php arrays, including deduplication of one-dimensional arrays and two-dimensional arrays. For more information, see.
First, let's look at the method for removing repeated items from one-dimensional arrays.
Use the array_unique function, for example:
Output result: Array ([0] => apple [1] => banana [2] => pear [4] => wail [5] => watermalon ).
Let's take a look at the method for removing duplicate items from two-dimensional arrays.
Two-dimensional arrays can be discussed in two cases: one is that the values of one-key names cannot be repeated, and the other is that the values of one-dimensional arrays cannot be identical, the duplicate items are deleted.
Use specific examples to describe.
1. because the values of one-click names cannot be repeated, duplicate items are deleted.
$ V) {if (in_array ($ v [$ key], $ tmp_arr) // search for $ v [$ key] in the $ tmp_arr array, if yes, return true {unset ($ arr [$ k]);} else {$ tmp_arr [] = $ v [$ key] ;}} sort ($ arr ); // the sort function sorts the array. return $ arr;} $ aa = array ('id' => 123, 'name' => 'Zhang San '), array ('id' => 123, 'name' => 'Lily'), array ('id' => 124, 'name' => 'Wang 5 '), array ('id' => 125, 'name' => 'Zhao Liu'), array ('id' => 126, 'name' => 'Zhao Liu'); $ key = 'id'; assoc_unique (& $ aa, $ Key); print_r ($ aa); // by bbs.it-home.org?>
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 ))
2. duplicate items are deleted because the internal one-dimensional arrays cannot be identical.
$ V) {$ temp [$ k] = explode (",", $ v); // re-assemble the split array} return $ temp ;} $ aa = array ('id' => 123, 'name' => 'Zhang San'), array ('id' => 123, 'name' => 'Li si'), array ('id' => 124, 'name' => 'Wang 5'), array ('id' => 123, 'name' => 'Lily'), array ('id' => 126, 'name' => 'Zhao Liu'); $ bb = array_unique_fb ($ aa ); print_r ($ bb); // by bbs.it-home.org?>
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 )) |