对于比较关键的二阶关联数组 [英] Compare two associative arrays regarding the order of keys
问题描述
假设,我们有2个关联数组:
Suppose, we have 2 associative arrays:
<?php
$array1 = array(
1 => 2,
2 => 1,
);
$array2 = array(
2 => 1,
1 => 2,
);
它们包含相同的元素,但在不同的顺序。我想写一个比较函数,这将使真正的只有:
They contain same elements, but in different order. I wanted to write a comparison function, that will give true only if:
- 阵列具有相同的键=>值对。
- 对顺序是一样的。
所以,我尝试了以下内容:
So, I tried the following:
if ($array1 == $array2)
{
print "equal\n";
}
打印:等于
print count(array_diff_assoc($array1, $array1));
打印:0
然后,我创建了以下功能:
Then I created the following function:
function compare(&$array1, &$array2)
{
$n1 = count($array1);
$n2 = count($array2);
if ($n1 == $n2)
{
$keys1 = array_keys($array1);
$keys2 = array_keys($array2);
for ($i = 0; $i < $n1; ++$i)
{
if ($keys1[$i] == $keys2[$i])
{
if ($array1[$keys1[$i]] != $array2[$keys2[$i]])
{
return false;
}
}
else
{
return false;
}
}
return true;
}
else
{
return false;
}
}
这正常工作,但它不会工作,当我们要申请,因为阵列的嵌套数组这种严格的比较=
在这个运营商若!
This works correctly, but it won't work, when we want this strict comparison applied for nested arrays of arrays because of !=
operator in this if:
if ($array1[$keys1[$i]] != $array2[$keys2[$i]])
{
return false;
}
这可以是固定的,使用递归函数,按数据类型转换。但这种简化版本是好的适合我。
This can be fixed, using a recursive function, switching by type of data. But this simplified version was ok for me.
有没有这种类型的比较任何标准的解决方案?
Is there any standard solution for this type of comparison?
推荐答案
由于根据运营商数组描述一>,你想要什么是 ===
相等运算符。
As described under array operators, what you want is the ===
equality operator.
if ($array1 === $array2) {
echo "same key pairs and same element order\n";
}
这篇关于对于比较关键的二阶关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!