How to check if PHP associative arrays are equal, ignoring key ordering?

 ̄綄美尐妖づ 提交于 2019-12-08 08:05:57

问题


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.

  1. Copy the arrays
  2. Sort the Arrays
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!