没有内置函数的数组键比较

我有两个键值对数组。


数组如下:


$array1 = ["a" => 2, "b" => 3, "c" => 1, "d" => 2];

$array2 = ["c" => 1, "d" => 1, "a" => 2, "b" => 3, "x" => 4, "z" => 1];

问题陈述

我需要找到在有相同.


示例

为 3,因为 a、b 和 c 存在于中,并且分别具有相同的值 2、3 和 1。


尝试的方法countkeysarray1array2valueCountkeysarray1array2


foreach($array1 as $key => $value){ 

    if($array2.$key === $array1.$key){

       if($array2[$value] === $array1[$value]){

          $matchCount++;

       }

    }

}

注意:我不确定是否从数组对象访问键,因此使用dot(.),不知何故我获得了计数,但计数不正确。


墨色风雨
浏览 147回答 3
3回答

郎朗坤

<?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){&nbsp; &nbsp; $array_2_value = $array2[$key] ?? null;&nbsp; &nbsp; if($array_2_value !== null && $array_2_value === $value) $count++;}echo $count;演示:https://3v4l.org/BREbg您可以循环检查密钥是否存在具有相同值的键。如果是,我们将增加计数。您可以使用空合并运算符 ??&nbsp;来检查 是否存在。$array1$array2$key$array2

慕尼黑的夜晚无繁华

function countSameKeyAndValues(array $array1, array $array2): int&nbsp;{&nbsp; &nbsp; $sameKeys = array_keys(array_intersect($array1, $array2));&nbsp; &nbsp; $count = 0;&nbsp; &nbsp; foreach ($sameKeys as $key) {&nbsp; &nbsp; &nbsp; &nbsp; if ($array1[$key] === $array2[$key]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $count++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return $count;}

Qyouu

您可以使用循环遍历$array 1。foreach然后,您可以使用 for 检查 $array 2 的值。key$array1然后,如果该键的值存在,则可以检查该键的值是否相同$array1<?php&nbsp; &nbsp;$array1 = ["a" => 2, "b" => 3, "c" => 1, "d" => 2];&nbsp; &nbsp;$array2 = ["c" => 1, "d" => 1, "a" => 2, "b" => 3, "x" => 4, "z" => 1];&nbsp; &nbsp;$count = 0;&nbsp; &nbsp;foreach($array1 as $key => $value){&nbsp; &nbsp; &nbsp; $array2Value = $array2[$key] ?? null;&nbsp; &nbsp; &nbsp; if($array2Value !== null && $array2Value === $value)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $count++;&nbsp; &nbsp;}echo $count;
打开App,查看更多内容
随时随地看视频慕课网APP