在 PHP 中取这两个数组:
$array1 = [
2 => 'Search',
1 => 'Front-End / GUI'
];
$array2 = [
1 => 'Front-End / GUI',
2 => 'Search'
];
大多数数组比较函数不关心顺序。执行 anarray_diff
将导致一个空数组。
比较两个数组的顺序和最有效/最短/最干净的方法是什么:
- 显示它们是否相等(真/假)?
- 显示差异(例如 PHPUnit)?
理想情况下,在 PHPUnit 中运行$this->assertEquals( $array1, $array2 );
应该会产生类似的结果:
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
- 2 => 'Search'
- 1 => 'Front-End / GUI'
+ 1 => 'Front-End / GUI'
+ 2 => 'Search'
)
更新 - 解决方案
只有当所有元素都相同,只是顺序不同时,才会产生一种差异。PHP单元测试:
public function test...() {
$actual = someCall();
$expected = [...];
// tests for same elements
$this->assertEquals( $expected, $actual );
// tests for same order
$diff = $this->array_diff_order( $expected, $actual );
$this->assertTrue( $expected === $actual, "Failed asserting that two arrays are equal order.\n--- Expected\n+++ Actual\n@@ @@\n Array(\n$diff )" );
}
private function array_diff_order( $array1, $array2 ) {
$out = '';
while ((list($key1, $val1) = each($array1)) && (list($key2, $val2) = each($array2)) ) {
if($key1 != $key2 || $val1 != $val2) $out .= "- $key1 => '$val1' \n+ $key2 => '$val2'\n";
}
return $out;
}