-
- $aa=array("apple","banana","pear","apple","wail","watermalon");
- $bb=array_unique($aa);
- print_r($bb);
- ?>
Copy the code
Output result:
Array ( [0] => apple [1] => banana [2] => pear [4] => wail [5] => watermalon ) .
Second, duplicates of PHP two-dimensional array:
For two-dimensional arrays, we will discuss two situations. One is because the value of a certain key name cannot be repeated and duplicates are deleted;
The other is to remove duplicates because the internal one-dimensional arrays cannot be exactly the same.
Example 1, because the value of a certain key name cannot be repeated, delete the duplicates.
Code:
-
- function assoc_unique($arr, $key)
- {
- $tmp_arr = array();
- foreach($arr as $k => $v)
- {
- if(in_array ($v[$key], $tmp_arr))//Search whether $v[$key] exists in the $tmp_arr array. If it exists, return true
- { // bbs.it-home.org
- unset($arr[ $k]);
- }
- else {
- $tmp_arr[] = $v[$key];
- }
- }
- sort($arr); //sort function sorts the array
- return $arr;
- }
- $aa = array(
- array('id' => 123, 'name' => 'Zhang San'),
- array('id' => 123, 'name' => '李思') ,
- array('id' => 124, 'name' => '王五'),
- array('id' => 125, 'name' => 'Zhao Liu'),
- array( 'id' => 126, 'name' => 'Zhao Liu')
- );
- $key = 'id';
- assoc_unique(&$aa, $key);
- print_r($aa);
- ? >
-
Copy code
Output result: Array ( [0] => Array ( [id] => 123 [name] => Zhang San) [1] => Array ( [id] => 124 [name] => Wang Wu) [2] => Array ( [id] => 125 [name] => Zhao Liu)
[3] => Array ( [id] => 126 [name] => Zhao Liu ) )
Example 2: Delete duplicates because the internal one-dimensional arrays cannot be exactly the same.
Code:
-
- function array_unique_fb($array2D){
- foreach ($array2D as $v){
- $v = join(",",$v); //Dimension reduction can also be used implode, convert a one-dimensional array into a string connected by commas
- $temp[] = $v;
- } // bbs.it-home.org
- $temp = array_unique($temp); //Remove repeated characters String, that is, a repeated one-dimensional array
- foreach ($temp as $k => $v){
- $temp[$k] = explode(",",$v); //Then split the array Reassemble
- }
- return $temp;
- }
- $aa = array(
- array('id' => 123, 'name' => 'Zhang San'),
- array('id' => 123 , 'name' => '李思'),
- array('id' => 124, 'name' => '王五'),
- array('id' => 123, 'name' => '李思'),
- array('id' => 126, 'name' => 'Zhao Liu')
- );
- $bb=array_unique_fb($aa);
- print_r($bb)
- ?>
Copy the code
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 Liu ) ) |