Find array in array, in sequence

前端 未结 2 1311
轮回少年
轮回少年 2021-01-16 13:47

How to code up a [find-array-in-array] function?

Psuedo-code

Haystack:

array(0=a, 1=b, 2=a, 3=b, 4=c,         


        
2条回答
  •  我在风中等你
    2021-01-16 14:07

    My attempt at creating this function;

    function find_array_in_array($needle, $haystack) {
        $keys = array_keys($haystack, $needle[0]);
        $out = array();
        foreach ($keys as $key) {
            $add = true;
            $result = array();
            foreach ($needle as $i => $value) {
                if (!(isset($haystack[$key + $i]) && $haystack[$key + $i] == $value)) {
                    $add = false;
                    break;
                }
                $result[] = $key + $i;
            }
            if ($add == true) { 
                $out[] = $result;
            }
        }
        return $out;
    }
    
    $haystack = array('a', 'b', 'a', 'b', 'c', 'c', 'a', 'b', 'd', 'c', 'a', 'b', 'a', 'b', 'c');
    
    $needle = array('a', 'b', 'c');
    
    print_r(find_array_in_array($needle, $haystack));
    

    Outputs;

    Array
    (
        [0] => Array
            (
                [0] => 2
                [1] => 3
                [2] => 4
            )
    
        [1] => Array
            (
                [0] => 12
                [1] => 13
                [2] => 14
            )
    
    )
    

提交回复
热议问题