测试一个数组是否是另一个数组的子集 [英] Test if one array is a subset of another

查看:133
本文介绍了测试一个数组是否是另一个数组的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定一个数组是否是另一个数组的子集(第一个数组中的所有元素都出现在第二个数组中)?

How can I determine if one array is a subset of another (all elements in the first are present in the second)?

 $s1 = "string1>string2>string3>string4>string5>string6>";
 $arr1 = explode(">", $s1);
 $s2 = "string1>string4>string5";
 $arr2 = explode(">", $s2);

 $isSubset = /* ??? */

推荐答案

如果从字符串开始,则可以检查strstr($fullString,$subsetStr);.但这仅在所有字符具有相同顺序时才起作用:'abcd','cd'将起作用,而'abcd','ad'将不起作用.

If you start from strings, you could check strstr($fullString,$subsetStr);. But that'll only work when all chars have the same order: 'abcd','cd' will work, but 'abcd','ad' won't.

但是您应该知道PHP具有数组数组函数 TONS ,而不是编写自己的自定义函数,因此,它几乎不可能没有一个可以满足您需要的std函数它要做.在这种情况下,我建议array_diff:

But instead of writing your own, custom, function you should know that PHP has TONS of array functions, so its neigh on impossible that there isn't a std function that can do what you need it to do. In this case, I'd suggest array_diff:

$srcString = explode('>','string1>string2>string3>string4>string5');
$subset = explode('>','string3>string2>string5');
$isSubset = array_diff($subset,$srcString);
//if (empty($isSubset)) --> cf comments: somewhat safer branch:
if (!$isSubset)
{
    echo 'Subset';
    return true;
}
else
{
    echo 'Nope, substrings: '.implode(', ',$isSubset).' Didn\'t match';
    return false;
}

这篇关于测试一个数组是否是另一个数组的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆