我有两个数组,
$a= array(1,2,3,4,5);
$b= array(2,1,4,4,5);
我想打印 (4,5) 因为它是两个给定数组中相同位置的元素。
You should be able to use array_intersect_assoc()
like this:
$a = array(1,2,3,4,5);
$b = array(2,1,4,4,5);
$array = array_intersect_assoc($a, $b);
var_dump($array);
The array_intersect_assoc()
function performs similarly to array_intersect()
, however it adds an extra key check to validate that the keys match as well.
这个怎么样:
$length = count($a);
$same = array();
for($i = 0; $i < $length; $i++) {
if($a[$i] == $b[$i]) {
$same[] = $a[$i];
}
}
$c = array();
foreach($a as $key => $val) {
if($val == $b[$key]) {
$c[] = $val;
}
}
var_dump($c);
输出:
array(2) {
[0]=>
int(4)
[1]=>
int(5)
}