[英]How to compare two array based on matched values and order in PHP?
I have 2 array, I want to compare them by matched values and order and count of total eligible values.我有 2 个数组,我想通过匹配的值以及符合条件的总值的顺序和计数来比较它们。
$a = [A,B,C,D,E,F,G];
| | |
$b = [B,A,C,D,F,E,G];
In this case the output should be 3 .在这种情况下,输出应该是3 。 How can I achieve this with top performance?我怎样才能以最佳性能实现这一目标?
Update:更新:
I am not asking matched values only , values should matched at the same order as well.我不只是要求匹配的值,值也应该以相同的顺序匹配。
Array_diff_assoc will count what is not the same (4). Array_diff_assoc 将计算不相同的内容 (4)。
Count will count the number of items (7). Count 将计算项目的数量 (7)。
7-4 = 3. 7-4 = 3。
echo count($a) - count(array_diff_assoc($a,$b)); // 3
https://3v4l.org/OIknS https://3v4l.org/OIknS
Edit or just array_intersect_assoc编辑或只是 array_intersect_assoc
echo count(array_intersect_assoc($a,$b)); //3
Didn't cross my mind until now.直到现在我都没有想到。
Assuming that both arrays have the same size you can do it with a simple loop:假设两个数组的大小相同,您可以使用一个简单的循环来完成:
$count = 0;
foreach ($a as $key => $value) {
if ($value === $b[$key]) {
$count++;
}
}
var_dump($count);
If they have different sizes then you must check if the key exists in the second array too.如果它们的大小不同,那么您必须检查该键是否也存在于第二个数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.