PHP 比较数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/901815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:16:18  来源:igfitidea点击:

PHP compare array

phparrayscomparison

提问by hakre

Is there anyway to compare arrays in php using an inbuilt function, short of doing some sort of loop?

无论如何,是否可以使用内置函数比较 php 中的数组,而不是执行某种循环?

$a1 = array(1,2,3);
$a2 = array(1,2,3);

if (array_are_same($a1, $a2)) {
    // code here
}

Btw, the array values will not always be in the same order.

顺便说一句,数组值并不总是以相同的顺序排列。

回答by Alan Haggai Alavi

if ( $a == $b ) {
    echo 'We are the same!'
}

回答by hakre

Comparing two arrays to have equal values (duplicated or not, type-juggling taking into account) can be done by using array_diff()into both directions:

可以通过array_diff()在两个方向上使用来比较两个数组以具有相等的值(重复与否,类型杂耍考虑在内):

!array_diff($a, $b) && !array_diff($b, $a);

This gives TRUEif both arrays have the same values (after type-juggling). FALSEotherwise. Examples:

这给出了TRUE两个数组是否具有相同的值(在类型杂耍之后)。FALSE除此以外。例子:

function array_equal_values(array $a, array $b) {
    return !array_diff($a, $b) && !array_diff($b, $a);
}

array_equal_values([1], []);            # FALSE
array_equal_values([], [1]);            # FALSE
array_equal_values(['1'], [1]);         # TRUE
array_equal_values(['1'], [1, 1, '1']); # TRUE

As this example shows, array_diffleaves array keys out of the equation and does not care about the order of values either and neither about if values are duplicated or not.

如本例所示,array_diff将数组键排除在等式之外,也不关心值的顺序,也不关心值是否重复。



If duplication has to make a difference, this becomes more tricky. As far as "simple" values are concerned (only string and integer values work), array_count_values()comes into play to gather information about which value is how often inside an array. This information can be easily compared with ==:

如果重复必须有所作为,这将变得更加棘手。就“简单”值而言(只有字符串和整数值有效),array_count_values()它开始收集有关哪个值在数组中的频率的信息。这些信息可以很容易地与==

array_count_values($a) == array_count_values($b);

This gives TRUEif both arrays have the same values (after type-juggling) for the same amount of time. FALSEotherwise. Examples:

这给出了TRUE两个数组是否在相同的时间内具有相同的值(在类型杂耍之后)。FALSE除此以外。例子:

function array_equal_values(array $a, array $b) {
    return array_count_values($a) == array_count_values($b);
}

array_equal_values([2, 1], [1, 2]);           # TRUE
array_equal_values([2, 1, 2], [1, 2, 2]);     # TRUE
array_equal_values(['2', '2'], [2, '2.0']);   # FALSE
array_equal_values(['2.0', '2'], [2, '2.0']); # TRUE

This can be further optimized by comparing the count of the two arrays first which is relatively cheap and a quick test to tell most arrays apart when counting value duplication makes a difference.

这可以通过首先比较两个数组的计数来进一步优化,这是相对便宜的,并且可以快速测试以在计数值重复产生差异时区分大多数数组。



These examples so far are partially limited to string and integer values and no strict comparison is possible with array_diffeither. More dedicated for strict comparison is array_search. So values need to be counted and indexed so that they can be compared as just turning them into a key (as array_searchdoes) won't make it.

到目前为止,这些示例部分限于字符串和整数值,并且无法与array_diff两者进行严格的比较。更专门用于严格比较的是array_search. 因此需要对值进行计数和索引,以便可以将它们进行比较,因为仅将它们转换为键(array_search如此)是行不通的。

This is a bit more work. However in the end the comparison is the same as earlier:

这是一个多一点的工作。然而,最终的比较与之前的相同:

$count($a) == $count($b);

It's just $countthat makes the difference:

它只是$count使其中的差别:

    $table = [];
    $count = function (array $array) use (&$table) {
        $exit   = (bool)$table;
        $result = [];
        foreach ($array as $value) {
            $key = array_search($value, $table, true);

            if (FALSE !== $key) {
                if (!isset($result[$key])) {
                    $result[$key] = 1;
                } else {
                    $result[$key]++;
                }
                continue;
            }

            if ($exit) {
                break;
            }

            $key          = count($table);
            $table[$key]  = $value;
            $result[$key] = 1;
        }

        return $result;
    };

This keeps a table of values so that both arrays can use the same index. Also it's possible to exit early the first time in the second array a new value is experienced.

这会保留一个值表,以便两个数组可以使用相同的索引。也可以在第二个数组中第一次出现新值时提前退出。

This function can also add the strictcontext by having an additional parameter. And by adding another additional parameter would then allow to enable looking for duplicates or not. The full example:

此函数还可以通过附加参数来添加严格上下文。并且通过添加另一个附加参数将允许启用或不查找重复项。完整示例:

function array_equal_values(array $a, array $b, $strict = FALSE, $allow_duplicate_values = TRUE) {

    $add = (int)!$allow_duplicate_values;

    if ($add and count($a) !== count($b)) {
        return FALSE;
    }

    $table = [];
    $count = function (array $array) use (&$table, $add, $strict) {
        $exit   = (bool)$table;
        $result = [];
        foreach ($array as $value) {
            $key = array_search($value, $table, $strict);

            if (FALSE !== $key) {
                if (!isset($result[$key])) {
                    $result[$key] = 1;
                } else {
                    $result[$key] += $add;
                }
                continue;
            }

            if ($exit) {
                break;
            }

            $key          = count($table);
            $table[$key]  = $value;
            $result[$key] = 1;
        }

        return $result;
    };

    return $count($a) == $count($b);
}

Usage Examples:

用法示例:

array_equal_values(['2.0', '2', 2], ['2', '2.0', 2], TRUE);           # TRUE
array_equal_values(['2.0', '2', 2, 2], ['2', '2.0', 2], TRUE);        # TRUE
array_equal_values(['2.0', '2', 2, 2], ['2', '2.0', 2], TRUE, FALSE); # FALSE
array_equal_values(['2'], ['2'], TRUE, FALSE);                        # TRUE
array_equal_values([2], ['2', 2]);                                    # TRUE
array_equal_values([2], ['2', 2], FALSE);                             # TRUE
array_equal_values([2], ['2', 2], FALSE, TRUE);                       # FALSE

回答by pscheit

@Cleanshooter i'm sorry but this does not do, what it is expected todo: (so does array_diff mentioned in this context)

@Cleanshooter 很抱歉,但这不起作用,它是预期要做的:(在此上下文中提到的 array_diff 也是如此)

$a1 = array('one','two');
$a2 = array('one','two','three');

var_dump(count(array_diff($a1, $a2)) === 0); // returns TRUE

(annotation: you cannot use empty on functions before PHP 5.5) in this case the result is true allthough the arrays are different.

(注释:在 PHP 5.5 之前的函数上不能使用 empty )在这种情况下,尽管数组不同,但结果为真。

array_diff [...] Returns an array containing all the entries from array1 that are not present in any of the other arrays.

array_diff [...] 返回一个数组,其中包含 array1 中不存在于任何其他数组中的所有条目。

which does not mean that array_diffis something like: array_get_all_differences. Explained in mathematical sets it computes:

这并不意味着array_diff是这样的:array_get_all_differences。用数学集解释它计算:

{'one','two'} \ {'one','two','three'} = {}

which means something like all elements from first set without all the elements from second set, which are in the first set. So that

这意味着类似于第一组中的所有元素,而第二组中的所有元素都在第一组中。以便

var_dump(array_diff($a2, $a1));

computes to

计算为

array(1) { [2]=> string(5) "three" } 

The conclusion is, that you have to do an array_diffin "both ways" to get all "differences" from the two arrays.

结论是,您必须以array_diff“两种方式”进行操作才能从两个数组中获取所有“差异”。

hope this helps :)

希望这可以帮助 :)

回答by Murz

Also you can try this way:

你也可以试试这种方式:

if(serialize($a1) == serialize($a2))

回答by moonw

array_intersect()returns an array containing all the common values.

array_intersect()返回一个包含所有公共值的数组。

回答by Alex Martelli

Just check $a1 == $a2-- what's wrong with that?

只是检查$a1 == $a2- 那有什么问题?

回答by chichilatte

A speedy method for comparing array values which can be in any order...

一种用于比较可以按任何顺序排列的数组值的快速方法...

function arrays_are_same($array1, $array2) {
    sort($array1);
    sort($array2);
    return $array1==$array2;
}

So for...

因此对于...

    $array1 = array('audio', 'video', 'image');
    $array2 = array('video', 'image', 'audio');

arrays_are_same($array1, $array2)will return TRUE

arrays_are_same($array1, $array2)将返回 TRUE

回答by CJ Ramki

get the array from user or input the array values.Use sort function to sort both arrays. check using ternary operator. If the both arrays are equal it will print arrays are equal else it will print arrays are not equal. there is no loop iteration here.

从用户获取数组或输入数组值。使用 sort 函数对两个数组进行排序。使用三元运算符检查。如果两个数组相等,则打印数组相等,否则打印数组不相等。这里没有循环迭代。

sort($a1);
sort($a2);
echo (($a1==$a2) ? "arrays are equal" : "arrays are not equal");

回答by Tyron

Conclusion from the commentary here:

此处评论的结论:

Comparison of array values being equal (after type juggling) and in the same order only:

数组值的比较相等(在类型杂耍之后)并且仅以相同的顺序:

array_values($a1) == array_values($a2)

Comparison of array values being equal (after type juggling) and in the same order and array keys being the same and in the same order:

数组值相等(类型杂耍后)且顺序相同和数组键相同且顺​​序相同的比较:

array_values($a1) == array_values($a2) && array_keys($a1) == array_keys($a2)

回答by rcourtna

verify that the intersections count is the same as both source arrays

验证交叉点计数是否与两个源数组相同

$intersections = array_intersect($a1, $a2);
$equality = (count($a1) == count($a2)) && (count($a2) == count($intersections)) ? true : false;