3 回答
TA贡献1921条经验 获得超9个赞
<?php
$array1 = ["a" => 2, "b" => 3, "c" => 1, "d" => 2];
$array2 = ["c" => 1, "d" => 1, "a" => 2, "b" => 3, "x" => 4, "z" => 1];
$count = 0;
foreach($array1 as $key => $value){
$array_2_value = $array2[$key] ?? null;
if($array_2_value !== null && $array_2_value === $value) $count++;
}
echo $count;
您可以循环检查密钥是否存在具有相同值的键。如果是,我们将增加计数。您可以使用空合并运算符 ??
来检查 是否存在。$array1
$array2
$key
$array2
TA贡献1864条经验 获得超6个赞
function countSameKeyAndValues(array $array1, array $array2): int
{
$sameKeys = array_keys(array_intersect($array1, $array2));
$count = 0;
foreach ($sameKeys as $key) {
if ($array1[$key] === $array2[$key]) {
$count++;
}
}
return $count;
}
TA贡献1786条经验 获得超11个赞
您可以使用循环遍历$array 1。foreach
然后,您可以使用 for 检查 $array 2 的值。key$array1
然后,如果该键的值存在,则可以检查该键的值是否相同$array1
<?php
$array1 = ["a" => 2, "b" => 3, "c" => 1, "d" => 2];
$array2 = ["c" => 1, "d" => 1, "a" => 2, "b" => 3, "x" => 4, "z" => 1];
$count = 0;
foreach($array1 as $key => $value){
$array2Value = $array2[$key] ?? null;
if($array2Value !== null && $array2Value === $value)
$count++;
}
echo $count;
- 3 回答
- 0 关注
- 93 浏览
添加回答
举报