1. Can directly use PHP's built-in function array_intersect ()
Array Array_intersect (array $array 1, array $array 2 [, array $ ...])
Array_intersect () returns an array that contains all the values in Array1 that also appear in all other parameter arrays. Note that the key name remains unchanged.
Code:
Copy Code code as follows:
<?php
$array 1 = Array ("A" => "green", "Red", "blue");
$array 2 = Array ("B" => "green", "yellow", "red");
$result = Array_intersect ($array 1, $array 2);
?>
Output results:
Array ([a] => green [0] => Red)
2. You can also write an algorithm yourself:
Copy Code code as follows:
<?php
function My_array_same ($a) {
$b = Array_unique ($a);
$r = Array_diff_key ($a, $b);
echo "<pre>";
$k =var_dump (Array_unique ($r));
return $k;
}
$a = Array ("Red", "green", "pink", "red", "yellow", "pink", "red");
$r =my_array_same ($a);
Var_dump (Array_unique ($r));
?>
Output results:
Array (2) {
[3]=>
String (3) "Red"
[5]=>
String (4) "Pink"
}
3. You can also write this:
Copy Code code as follows:
<?php
function My_array_intersect ($arr 1, $arr 2) {
For ($i =0 $i <count ($arr 1); $i + +) {
$temp []= $arr 1[$i];
}
For ($i =0 $i <count ($arr 1); $i + +) {
$temp []= $arr 2[$i];
}
Sort ($temp);
$get =array ();
for ($i =0; $i <count ($temp); $i + +) {
if ($temp [$i]== $temp [$i +1])
$get []= $temp [$i];
}
return $get;
}
$array 1 = Array ("Green", "Red", "blue");
$array 2 = Array ("green", "yellow", "red");
echo "<pre>";
Print_r (My_array_intersect ($array 1, $array 2));
echo "<pre/>";
?>
If it's a one-dimensional array, the third algorithm is faster than the first. All of these algorithms apply to one-dimensional arrays, so how do multidimensional arrays find the same elements?
Thought: The multi-dimensional array can be transformed into one-dimensional array, and then the output of the algorithm is then used.
Code:
Copy Code code as follows:
function Toarr ($arr) {//array is recursive, returned as a string
foreach ($arr as $k => $v) {
if (!is_array ($v)) {
$str. = $v. " ";
}
else{
$str. =toarr ($v);
}
}
return $str;
}/* recursive function End */
The upper-form converts multidimensional arrays into strings and then transforms them into one-dimensional arrays using the Expode function.
Lenovo, the database returns the name of a field is the same reason, of course, through the SQL statement can be implemented.