我有两个数组,分别是$a和$b,其中数组的值相同,但元素的索引不同。 $a Array ( [0] => there is bald spot on the inside or outside of tyre [1] => uneven tyre wear ) $b Array ( [0] => uneven tyre wear [1] => there is bald spot on the inside or outside of tyre ) 但是当我使用进行比较时$a == $b,false即使数组中的元素相同(即使元素的位置不同),它也会返回。
之前给出的解决方案是
$a = Array ( 0 => 'there is bald spot on the inside or outside of tyre', 1 => 'uneven tyre wear'
);
$b = Array ( 0 => 'uneven tyre wear', 1 => 'there is bald spot on the inside or outside of tyre' );
if(count(array_diff($a,$b)) == 0){ echo "both array are identical";
} 但是如果我从$ a中删除一个元素
$a = Array ( 0 => 'there is bald spot on the inside or outside of tyre' //1 => 'uneven tyre wear'
); 如果使用上述解决方案,它仍然显示相同的内容。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
在您的情况下,如果您想比较两个数组是否包含相同的元素,不考虑顺序和数量,您可以使用以下方法:
$a = Array ( 0 => 'there is bald spot on the inside or outside of tyre' );
$b = Array ( 0 => 'uneven tyre wear', 1 => 'there is bald spot on the inside or outside of tyre' );
// 将数组转换为集合(或使用 array_unique 来去重,但这里直接用集合更直观)
$a_set = array_unique($a);
$b_set = array_unique($b);
// 比较两个集合是否相同
if(count(array_diff($a_set, $b_set)) == 0 && count(array_diff($b_set, $a_set)) == 0){
echo "Both arrays contain the same elements.";
} else {
echo "Arrays do not contain the same elements.";
}
这个解决方案首先通过array_unique
函数去除了每个数组中的重复元素,然后使用array_diff
来检查两个数组去重后的集合是否有差异。如果两个集合相互之间没有差异(即它们包含完全相同的元素,无论数量和顺序),则会输出“Both arrays contain the same elements.”。
请注意,这种方法不仅忽略了元素的顺序,也忽略了元素出现的次数,仅检查两个数组是否包含相同的元素集合。如果需要同时考虑元素的个数,请调整方法以适应具体需求。