繁体   English   中英

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

所以现在我想做什么

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

如果一个元素中有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

小提琴

使用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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM