如何检查一个数组是否包含一个序列中的另一个数组?

时间:2019-02-28 22:32:02

标签: php indexing contains

我有两个数组:

$a = array("w","c","d","e","g","h");
$b = array("c","d","e");
$c = array("c","e","d");

如果我们检查$ a包含$ b或$ a包含$ c,则应该返回“ TRUE”,因为$ b的索引与$ a和$ c顺序相同,即它们都具有$“ c”,“ d “,” e,它们以$ a的顺序出现。 但是,如果$b = array("c", "g", "d"),我们应该得到false,因为它具有所有元素,但是它们在$ a中的顺序不正确。

1 个答案:

答案 0 :(得分:1)

这样的事情应该可以解决问题:

$a = ["w","c","d","e","g","h"];
$b = ["c","d","e"];
$c = ["c","e","d"];
function containsSequence($arr, $subArray){
    $keys = array_keys($arr, $subArray[array_keys($subArray)[0]]); 
    foreach($keys as $k) {
        if(array_slice($arr, $k, count($subArray)) == $subArray){
            return true;    
        }
    }
    return false;
}
echo 'Contains sequence: '.(containsSequence($a,$b)?'yes:':'no');
echo 'Contains sequence: '.(containsSequence($a,$c)?'ues':'no');