查找数组的元素在 PHP 中的另一个数组中


find array's elements are in another array in PHP

数组 A:

486 987

阵列 B:

247-16-02-2009 486-16-02-2009 562-16-02-2009 1257-16-02-2009 486-16-02-2009 

我想搜索并列出数组 B 中匹配的所有数组 A 元素,例如:486-16-02-2009(两次)。

您可以通过

$arrayA内爆到模式中使用正则表达式。 这将在$arrayB项目中的任何位置找到$arrayA项目:

$pattern = implode("|", $arrayA);
$result  = preg_grep("/$pattern/", $arrayB);

若要仅在$arrayB项的开头匹配,请使用^锚点"/^$pattern/"

您可能希望通过preg_quote()运行$arrayA元素,如果其中可能存在特殊模式字符。

你可以做这样的事情,但它可能不如使用像array-intersect这样的php内置函数,因为我们正在进入循环地狱。如果任一数组变得太大,您的脚本将缓慢爬行。

foreach ($arrB as $values) {
    foreach ($arrA as $compare) {
        if (substr($values, 0, strlen($compare)) == $compare) {
            //do stuff
        }
    }
}

您必须遍历两个数组以搜索每种情况:

工作示例:http://ideone.com/pDCZ1R

<?php

$needle = [486, 987];
$haystack = ["247-16-02-2009", "486-16-02-2009", "562-16-02-2009", "1257-16-02-2009", "486-16-02-2009"];
$result = array_filter($haystack, function($item) use ($needle){
    foreach($needle as $v){
        if(strpos($item, strval($v)) !== false){
            return true;
        }
    }
    return false;
});
print_r($result);

与其他两个答案有些相似,但这是我的方法:

$matches = array(); // We'll store the matches in this array
// Loop through all values we are searching for
foreach($arrayA as $needle){
    // Loop through all values we are looking within
    foreach($arrayB as $haystack){
        if(strpos($needle, $haystack) !== false){
            // We found a match.
            // Let's make sure we do not add the match to the array twice (de-duplication):
            if(!in_array($haystack, $needle, true)){
                // This match does not already exist in our array of matches
                // Push it into the matches array
                array_push($matches, $haystack);
            }
        }
    }
}

注意此解决方案使用in_array()来防止匹配重复。如果您希望匹配多个值的匹配项多次显示,则只需删除!in_array(...)作为其条件的 if 语句即可。