按顺序比较PHP中数组的最有效方法? [英] Most efficient way to compare arrays in PHP by order?

查看:88
本文介绍了按顺序比较PHP中数组的最有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中使用这两个数组:

Take these two arrays in PHP:

$array1 = [
    2 => 'Search',
    1 => 'Front-End / GUI'
];
$array2 = [
    1 => 'Front-End / GUI',
    2 => 'Search'
];

大多数数组比较函数不关心顺序.进行array_diff将导致一个空数组.

Most of the array comparison functions do not care about order. Doing an array_diff will result in an empty array.

比较两个数组的有序和最有效/最短/最干净的方法是什么?

What's the most efficient / shortest / cleanest way to compare two arrays with regard to order and:

  1. 显示它们是否相等(对/错)?
  2. 显示差异(例如对于PHPUnit)吗?

理想情况下,在PHPUnit中运行$this->assertEquals( $array1, $array2 );应该会产生类似以下内容:

Running $this->assertEquals( $array1, $array2 ); in PHPUnit ideally should yield something like:

Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
 Array (
-    2 => 'Search'
-    1 => 'Front-End / GUI'
+    1 => 'Front-End / GUI'
+    2 => 'Search'
 )

更新-解决方案

仅当所有元素都相同(只是顺序不同)时,这才生成排序差异. PHPUnit测试:

Update - Solution

This generates a sort-of diff only if all elements are same, just in different order. PHPUnit Tests:

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;
}

推荐答案

您可以只使用===运算符

$array = array(1 => "test", 2=> "testing");
$array2 = array(1 => "test", 2=> "testing");

var_dump($array === $array2);

$array2 = array(2 => "test", 1=> "testing");
var_dump($array === $array2);

返回

boolean true
boolean false

然后使用array_diff_assoc()查找差异

then use array_diff_assoc() to find the differences

while ((list($key1, $val1) = each($array)) && (list($key2, $val2) = each($array2)) ) {
    if($key1 != $key2 || $val1 != $val2) echo "- $key1 - $val1 \n + $key2 - $val2";
}

应该为订单提供一些输出

Should give some output for order

使用数组可以给我

  • 2-搜索+ 1-前端/GUI
  • 1-前端/GUI + 2-搜索

您可以将输出更改为所需的方式

you can change the output to how ever you need it

这篇关于按顺序比较PHP中数组的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆