How to code up a [find-array-in-array]
function?
Psuedo-code
Haystack:
array(0=a, 1=b, 2=a, 3=b, 4=c, 5=c, 6=a, 7=b, 8=d, 9=c, 10=a, 11=b, 12=a, 13=b, 14=c);
Needle:
array(a, b, c);
Return:
array ( array (2, 3, 4), array(12, 13, 14) )
Desired: The Keys from Haystack that match Needle. The above should give 2 matches:
- match = Haystack 2-4
- match = Haystack 12-14
It should not find "a b"
, "a b d"
nor "c a b"
etc.,
only instances of each value in Needle - in the specified order.
I'd like to make it a function so I can run it repeatedly (I have lots of these patterns).
I've tried doing this with nested foreachs, and driven myself nuts with counters etc.
I get to a certain point, and am unable to separate matches from non-matches.
(Surprised there isn't a built in function? in_array
and array_intersect
seem to be for individual values only, not collections?)
$haystack = array('a','b','a','b','c','d','a','b','c');
$needle = array('a','b','c');
$CountH = count($haystack); echo $CountH."<br/>";
$CountN = count($needle); echo $CountN."<br/>";
$matches ='';
foreach ($haystack as $key1=>$haystackval){
foreach ($needle as $key2=>$needleval) {
$fail = '0';
//if (in_array($needleval, $haystack)) {
if ($key2[$needleval] === $haystackval && $fail === '0') {
echo "Got needleval - ".$needleval ."<br/>";
}
else { $fail='1';
}
}
}