开发者社区 问答 正文

如何检查一个php数组,该数组包含与其他数组相同的值

我有两个数组,分别是$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'

); 如果使用上述解决方案,它仍然显示相同的内容。

展开
收起
社区秘书 2019-12-09 16:26:58 605 分享 版权
阿里云 AI 助理回答

在您的情况下,如果您想比较两个数组是否包含相同的元素,不考虑顺序和数量,您可以使用以下方法:

$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.”。

请注意,这种方法不仅忽略了元素的顺序,也忽略了元素出现的次数,仅检查两个数组是否包含相同的元素集合。如果需要同时考虑元素的个数,请调整方法以适应具体需求。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答分类:
问答标签:
问答地址: