【问题标题】:counting matching elements of multiple arrays [duplicate]计算多个数组的匹配元素[重复]
【发布时间】:2018-12-31 01:19:10
【问题描述】:

我正在循环两个关联数组。第一个是标签,第二个是数据。我想计算每个数据项中每个标签的匹配项。 例如

$tags= array("japan", "china", "usa")
$data=array("something...", "something..", "something..")

我想计算每个帖子中有多少次日本,每个帖子中有多少次中国,每个帖子中有多少次美国。不幸的是,我只得到了第一个标签输入日本的计数结果。如何纠正这种情况??

foreach ($tags as $tag) {   
    foreach ($data as $value) {
        $count= substr_count($value,$tag);
    }   

【问题讨论】:

  • 您在哪里创建/分配$data?当你不在任何地方使用$result 时,$result=array(); 的意义何在?

标签: php arrays loops associative-array


【解决方案1】:

将结果放入以标签为键的关联数组中,并使用+= 增加该标签的值。

$results = array();
foreach ($tags as $tag) {
    $results[$tag] = 0;
    foreach ($data as $value) {
        $results[$tag] += substr_count($value, $tag);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多