1. You can directly use PHP’s built-in function array_intersect()
array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
array_intersect() returns an array, This array contains all values in array1 that also appear in all other parameter arrays. Note that the key names remain unchanged.
Code:
Copy code The code is as follows:
$array1 = array(" a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
?>
Output result:
Array( [a] => green [0] => red)
2. You can also write an algorithm yourself:
Copy the code The code is as follows:
< ?php
function my_array_same($a){
$b = array_unique($a);
$r = array_diff_key($a,$b);
echo "
";
$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 result:
array(2) {
[3]=>
string(3) "red"
[5]=>
string(4) "pink "
}
3. You can also write:
Copy the code The code is as follows:
function my_array_intersect($arr1,$arr2){
for($i=0;$i
$temp[] =$arr1[$i];
}
for($i=0;$i$temp[]=$arr2[$i];
}
sort($temp);
$get=array();
for($i=0;$iif ($temp[$i]==$temp[$i+1])
$get[]=$temp[$i];
}
return $get;
}
$array1 = array("green", "red", "blue");
$array2 = array("green", "yellow", "red");
echo "" ;
print_r(my_array_intersect($array1, $array2));
echo "";
?>
If it is a one-dimensional array , the third algorithm is faster than the first one. The above algorithms are all suitable for one-dimensional arrays, so how to find the same elements in multi-dimensional arrays?
Idea: You can convert a multi-dimensional array into a one-dimensional array, and then use the above algorithm to output it.
Code:
Copy code The code is as follows:
function toarr($arr){ //Yes The array is recursed and returned as a string
foreach ($arr as $k=>$v){
if (!is_array($v)) {
$str.=$v." ";
}
else{
$str.=toarr($v);
}
}
return $str;
}/*End of recursive function*/
The above formula converts the multi-dimensional array into a string, and then uses the expode function to convert it into a one-dimensional array.
Think about it, this is also the case when the database returns the value of a certain field with the same name. Of course, it can also be achieved through sql statements.
http://www.bkjia.com/PHPjc/325862.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325862.htmlTechArticle1. You can directly use PHP’s built-in function array_intersect() array array_intersect ( array $array1 , array $array2 [, array $ ... ] ) array_intersect() returns an array containing...