问题
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:
- Arrays have the same key => value pairs.
- Order of pairs is the same.
So, I tried the following:
1 try
if ($array1 == $array2)
{
print "equal\n";
}
Prints: equal
2 try
print count(array_diff_assoc($array1, $array1));
Prints: 0
My custom function
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?
回答1:
As described under array operators, what you want is the === equality operator.
if ($array1 === $array2) {
echo "same key pairs and same element order\n";
}
回答2:
can you try the this below one. which returns true if the key=>value and will be in any order otherwise returns false
$array1 = array(
1 => 2,
2 => 1);
$array2 = array(
2 => 1,
1 => 2);
var_dump(compareArray($array1,$array2));
function compareArray ($array1, $array2)
{
foreach ($array1 as $key => $value)
{
if ($array2[$key] != $value)
{
return false;
}
}
return true;
}
来源:https://stackoverflow.com/questions/17924178/compare-two-associative-arrays-regarding-the-order-of-keys