PHP将所有数组值搜索到另一个数组值中

时间:2014-05-27 00:41:41

标签: php arrays

好的,这就是我想做的事情

我有一个包含关键字的数组

$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');

我有另一个包含我的全部标题的数组

让我们说

$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.','Cristiano Ronaldo is World Soccer's Player of the Year 2013.','Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona','','');

所以现在我想做什么

是在每个titles数组元素

中循环我的keywords数组

如果一个元素中有3个关键字,那就做点什么

例如

$titiles[0] // this one has these words => Madrid , cup club

所以这个关键词至少包含3个单词

因此,如果每个元素有3个或更多关键字,则回显该数组元素。

关于如何使这个工作的任何想法?

3 个答案:

答案 0 :(得分:4)

foreach ($titles as $t){

$te=explode(' ',$t);

$c=count(array_intersect($te,$keywords));

if($c >=3){
echo $t.' has 3 or more matches';
}

} 

现场演示:http://codepad.viper-7.com/7kUUEK

2个匹配项是您当前的最大值

如果您希望马德里匹配马德里

$keywords=array_map('strtolower', $keywords);
foreach ($titles as $t){

$te=explode(' ',$t);
$comp=array_map('strtolower', $te);

$c=count(array_intersect($comp,$keywords));



   if($c >=3){
   echo $t.' has 3 or more matches';
   }

} 

http://codepad.viper-7.com/itdegA

答案 1 :(得分:2)

或者,您也可以使用substr_count()来获取出现次数。考虑这个例子:

$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');
$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.',"Cristiano Ronaldo is World Soccer's Player of the Year 2013.","Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona",'','');
$count = 0;
$data = array();
foreach($titles as $key => $value) {
    $value = strtolower($value);
    $keys = array_map('strtolower', $keywords);
    foreach($keys as $needle) {
        $count+= substr_count($value, $needle);
    }
    echo "In title[$key], the number of occurences using keywords = " .$count . '<br/>';
    $count = 0;
}

示例输出:

In title[0], the number of occurences using keywords = 3
In title[1], the number of occurences using keywords = 2
In title[2], the number of occurences using keywords = 2
In title[3], the number of occurences using keywords = 0
In title[4], the number of occurences using keywords = 0

Fiddle

答案 2 :(得分:1)

使用array_intersect更简单:     

$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');

$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.','Cristiano Ronaldo is World Soccer\'s Player of the Year 2013.','Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona');

foreach($titles as $title) {
    if (count(array_intersect(explode(' ',strtolower($title)), $keywords)) >= 3) {
        //stuff
    }
}