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


PHP Search all array values into another each array value

好的,这是我想做的

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

$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','','');

所以现在我想做的是

是在每个标题数组元素中循环我的关键字数组

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

例如

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

所以这个是有至少3个字的我的关键字

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

你知道怎么做吗?

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

或者,您也可以使用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

使用array_incross更简单:

$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
    }
}