搜索两个数组中的单词

时间:2014-02-16 18:37:52

标签: php arrays

我正在尝试搜索两个数组并返回数组2中数组1中匹配的匹配单词的索引。以下是数组:

$array1 = array('hello how are you', 'hello I am fine');
$array2 = array('hello','how');

我正在尝试以下代码并返回0,1这很好。但我只想返回0.我希望它只返回数组中存在两个单词的位置。

 foreach ($array1 as $reference => $array) {
    foreach($array2 as $key => $word) {
       if(strpos($array, $word) !== false) { 
           echo $reference, PHP_EOL;
           break;
       }    
    }    
 }

1 个答案:

答案 0 :(得分:1)

您需要跟踪$array2中每个实体与$array1中每个实体进行核对的每个实体,然后在内部循环后进行比较,以确定$array2中的所有元素是否都存在于$array1中1}}。这是一个例子:

foreach($array1 as $reference => $array) {
    $contains = 0;
    foreach($array2 as $key => $word) {
        if(strpos($array, $word) !== false) {
            $contains++;
        } else {
            // for performance reasons, e.g. if you have a large array,
            // you should break the loop here if the word isn't in the
            // original array
            break;
        }
    }
    if($contains == count($array2)) {
        // $array contains all words from $array2
        echo $reference . PHP_EOL;
    } else {
        // $array doesn't contain all the words     
    }
}