简体   繁体   English

PHP中的多维数组比较

[英]Multidimensional arrays comparison in PHP

When comparing arrays The Documentation says 比较数组时,文档

$a == $b Equality TRUE if $a and $b have the same key/value pairs. $ a == $ b相等如果$ a和$ b具有相同的键/值对,则为TRUE。

Though when comparing with multidimensional arrays this doesn't seem to be the case 虽然在与多维数组进行比较时似乎并非如此

$a = array(
  array("test"),
  array("testing"),
);
$b = array(
  array("testing"),
  array("test"),
);

var_dump($a);
var_dump($b);
var_dump($a == $b);

returns 回报

array(2) {
  [0] =>
  array(1) {
    [0] =>
    string(4) "test"
  }
  [1] =>
  array(1) {
    [0] =>
    string(7) "testing"
  }
}
array(2) {
  [0] =>
  array(1) {
    [0] =>
    string(7) "testing"
  }
  [1] =>
  array(1) {
    [0] =>
    string(4) "test"
  }
}
bool(false)

Same array, Different order. 相同的数组,不同的顺序。 array diff returns correctly though. 数组diff虽然正确返回。

Is this an expected feature ? 这是预期的功能吗? I know i can compare with array_diff($a,b) + array($b, $a). 我知道我可以与array_diff($ a,b)+ array($ b,$ a)比较。 Im not sure why the == doesnt work though 我不确定为什么==无效

This is because your arrays are different in the leaf nodes. 这是因为叶节点中的数组不同。

In your first array 0 = test and in your second array 0 = testing . 在第一个数组中0 = test ,在第二个数组中0 = testing

Use === comparison for taking care about keys order. 使用===比较来注意按键顺序。

Check this source: 检查此来源:

Compare multidimensional arrays in PHP 比较PHP中的多维数组

regards 问候

== sign allows for comparison of arrays in any order, it will internally use a sort on the master array and do the === comparision. ==符号允许以任何顺序比较数组,它将在内部对主数组使用排序并进行===比较。

However it does not do a sort on the sub-arrays, you will need to do that manually before the comparison 但是,它不会对子数组进行排序,因此您需要在比较之前手动进行排序

NOTE : see == & === difference details here 注意 :请参阅==&=== 此处的差异详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM