php-比较具有重复值的数组

时间:2018-12-17 13:43:38

标签: php arrays

我需要比较而不会删除任何值),但两个数组中的每个数组都可以具有重复的值,例如我有那两个数组:

$options = ['G', 'W'];
$selectedOptions = ['G', 'G', 'W'];

这应该返回FALSE。下面是我的代码。它很好用,但仅适用于唯一值,如何为重复的值“升级”?

$mergeOptions = array_merge($selectedOptions, $options);
$intersect = array_intersect($selectedOptions, $options);
$diff = array_diff($mergeOptions, $intersect);

if (count($diff) === 0) {
    // $options are 'equal' to $selectedOptions
} else {
    // $options are not 'equal' to $selectedOptions
}

更多示例:

| selected | options | result |  
+----------+---------+--------+  
|  G, G, W |  G, W   |  FALSE |
+----------+---------+--------+
|   G, W   |  G, W   |  TRUE  |
+----------+---------+--------+
| G, P, W  | G, G, W |  FALSE |
+----------+---------+--------+
| G, P, G  | P, G, G |  TRUE  |
+----------+---------+--------+

1 个答案:

答案 0 :(得分:3)

您可以使用sort对数组进行排序,然后进行比较。

$a = ["P", "G", "G"];
$b = ["G", "P", "G"];
sort($a);
sort($b);

if ($a == $b) {
    echo "TRUE \n";
} else {
    echo "FALSE... \n";
}