duanfengshang1088 2013-02-01 07:00
浏览 88
已采纳

在嵌套数组中使用substr_count

I'm trying to pull out certain groups of keywords from a block of text using substr_count and have it count how many times the words in each group appears.

I've created an array called $keywords, within it is another set of arrays which contain the actual keywords I am looking for.

This is my current code:

$textDump = "random bunch of text";

$keyWordsSports = array("nba", "raptor", "ufc", "basektball", "gym", "mma", "realgm", "running");
$keyWordsTech = array("apple", "rim", "blackberry", "facebook", "twitter", "google" );
$keywords = array($keyWordsSports, $keyWordsTech);
foreach ($keywords as $item){
    foreach ($item as $newItem){
        $number += substr_count(strtolower($textDump), strtolower($newItem));
        echo $number;
    };
};

My problem is that it counts all the keywords within all the arrays and adds everything together, what I want is just the total for each group of keywords. Any ideas on what I should do?

  • 写回答

3条回答 默认 最新

  • dougongyou7364 2013-02-01 07:05
    关注
    $keywords = array("sports"=>$keyWordsSports, "tech"=>$keyWordsTech);
    $count=array("sports"=>0,"tech"=>0);
    foreach ($keywords as $key=>$item){
        foreach ($item as $newItem){
            $count[$key] += substr_count(strtolower($textDump), strtolower($newItem));
        }
    }
    print_r($count);
    

    Edit: Live example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器