本文介绍了比较在PHP阵列,而不关心顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,$ a和$ b在这里了,需要检查它们是否含有相同的元素(独立顺序)。我想使用

I have two arrays, $a and $b here, and need to check if they contain exactly the same elements (independently of the order). I am thinking of using

if (sizeof($a)==sizeof($b) AND array_diff($a,$b)==array())
{

}

不过,我是新来的PHP,所以我不知道?有没有更好的办法

But I am new to PHP, so I wonder: Is there a better way?

因为我需要为一组,也许我不应该在所有使用数组但别的东西来使用它们。

Since I need to use them as sets, maybe I should not use arrays at all but something else.

推荐答案

好了,我们可以做这样的事情:

Well, we can do something like this:

if (count(array_diff(array_merge($a, $b), array_intersect($a, $b))) === 0) {
    //they are the same!
}

它的工作原理,其原因是会带来很大的阵列同时具有的所有元素 $ A $ b (一切都在元素为 $ A $ b ,或两者)。 将创建一个数组有凡在都只有 $ A $ b 的元素。因此,如果它们是不同,,必须有不同时出现在阵列的至少一种元素...

The reason it works, is that array_merge will make a big array that has all the elements of both $a and $b (all the elements that are in either $a, $b, or both). array_intersect will create an array that has all the elements that are in both $a and $b only. So if they are different,, there must be at least one element that does not appear in both arrays...

另外请注意,不是实际的功能/结构,这是一个别名。我建议使用计数()为了清晰...

Also note that sizeof is not an actual function/construct, it's an alias. I'd suggest using count() for clarity...

这篇关于比较在PHP阵列,而不关心顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:23