PHP outputs several processing methods for the element with multiple names in the array. For more information, see
1. you can directly use the php built-in function array_intersect ()
Array array_intersect (array $ array1, array $ array2 [, array $...])
Array_intersect () returns an array containing all values that appear in the array of all other parameters at the same time in array1. Note that the key name remains unchanged.
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 by yourself:
The code is as follows:
Function my_array_same ($ ){
$ B = array_unique ($ );
$ 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 ($ );
Var_dump (array_unique ($ r ));
?>
Output result:
Array (2 ){
[3] =>
String (3) "red"
[5] =>
String (4) "pink"
}
3. it can also be written as follows:
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; $ I
If ($ 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 applicable to one-dimensional arrays. how can we find the same elements in multi-dimensional arrays?
Idea: you can convert multi-dimensional arrays into one-dimensional arrays and then use the above algorithm to output them.
Code:
The code is as follows:
Function toarr ($ arr) {// recursively returns an array in the form of a string
Foreach ($ arr as $ k =>$ v ){
If (! Is_array ($ v )){
$ Str. = $ v ."";
}
Else {
$ Str. = toarr ($ v );
}
}
Return $ str;
}/* End of the recursive function */
Convert a multi-dimensional array to a string, and then use the expode function to convert it to a one-dimensional array.
In retrospect, this is also true for the database to return the value of a field with the same name. of course, this can also be achieved through SQL statements.