Duplicate entries for one-dimensional arrays:
Use the Array_unique function to use the following example:
Copy Code code as follows:
<?php
$aa =array ("Apple", "banana", "pear", "apple", "wail", "Watermalon");
$BB =array_unique ($AA);
Print_r ($BB);
?>
The results are as follows: Array ([0] => Apple [1] =>banana [2] => pear [4] => wail [5]=>).
Duplicate entries for two-dimensional arrays:
For two-dimensional arrays We discuss two situations, one is because the value of a key cannot be duplicated, a duplicate item is deleted, and the other is to delete duplicates because the inner one-dimensional array cannot be exactly the same, as illustrated below:
㈠ Delete duplicates because the value of a key name cannot be duplicated
Copy Code code as follows:
<?php
function Assoc_unique ($arr, $key)
{
$tmp _arr = Array ();
foreach ($arr as $k => $v)
{
if (In_array ($v [$key], $tmp _arr))//Search $v[$key] is present in the $tmp_arr array, if present returns True
{
Unset ($arr [$k]);
}
else {
$tmp _arr[] = $v [$key];
}
}
Sort ($arr); Sort function Sorts by array
return $arr;
}
$aa = Array (
Array (' ID ' => 123, ' name ' => ' John '),
Array (' ID ' => 123, ' name ' => ' Dick '),
Array (' ID ' => 124, ' name ' => ' Harry '),
Array (' ID ' =>, ' name ' => ' Zhao Liu '),
Array (' ID ' => 126, ' name ' => ' Zhao Liu ')
);
$key = ' id ';
assoc_unique (& $aa, $key);
Print_r ($AA);
Display result is: Array ([0] => array ([ID] =>123 [name] => John) [1] => Array ([id] => 124 [name] => Harry) [2]=> Array ([ID] => [name]=> Zhao Liu) [3] => Array ([id]=> 126 [name] => Zhao Liu))
The ㈡ cannot be exactly the same because the inner one-dimensional array is not identical, but duplicates are deleted
Copy Code code as follows:
<?php
function ARRAY_UNIQUE_FB ($array 2D) {
foreach ($array 2D as $v) {
$v = Join (",", $v); dimensionality reduction, you can also use implode to convert a one-dimensional array into a comma-connected string
$temp [] = $v;
}
$temp =array_unique ($temp); Remove the duplicate string, which is a repeating one-dimensional array
foreach ($temp as $k => $v) {
$temp [$k] = Explode (",", $v); Re-assemble the disassembled array
}
return $temp;
}
$AA = Array (
Array (' ID ' => 123, ' name ' => ' John '),
Array (' ID ' => 123, ' name ' => ' Dick '),
Array (' ID ' => 124, ' name ' => ' Harry '),
Array (' ID ' => 123, ' name ' => ' Dick '),
Array (' ID ' => 126, ' name ' => ' Zhao Liu ')
);
$BB =ARRAY_UNIQUE_FB ($AA);
Print_r ($BB)
?>
Display Result: Array ([0] => Array ([0] =>123 [1] => John) [1] => Array ([0]=> 123 [1] => Lee IV) [2]=> array ( [0] => 124 [1]=> Harry) [4] => Array ([0]=> 126 [1] => Zhao Liu))