问题
Say I have two complex nested arrays in PHP, like these:
$a = array(
"x" => array(4, 5, 6),
"y" => array("z" => "foo", "q" => "bar")
);
$b = array(
"y" => array("q" => "bar", "z" => "foo"),
"x" => array(4, 5, 6)
);
(In this case, they're decoded JSON data from different sources). Assume the contents can be arbitrarily nested, but will not contain any circular references.
What's the most straightforward way to check if they are equal, ignoring key ordering? For example, the above two should compare equal. However, if $b["x"] were array(4, 6, 5) they would not be.
I could recursively ksort and compare the results, but I don't really want to modify either operand, and this seems like something that might have a simple one-line solution I don't know about. Is there anything out there?
回答1:
The best way of doing this, is already mentioned by you. But you forgot 1 thing.
- Copy the arrays
- Sort the Arrays
- Compare the 2
The same? Perfect. And you still have the original.
来源:https://stackoverflow.com/questions/10746649/how-to-check-if-php-associative-arrays-are-equal-ignoring-key-ordering