每个循环的substr_count double

时间:2014-03-27 15:35:02

标签: php arrays foreach count substring

我在数组中有一组推文文本。我试图看看这些文本中出现了多少次特定单词。

但它不仅仅是一个单词,而是从外部文件加载的单词数组。对于每个单词,都需要计数。

<?php
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);

$poswords = file('positive.csv');

$array = array("value", "bar", "ACCOMPLISHES", "valveworld", "able I am not bladiebla");
$count = 0;
foreach ($poswords as $posword) {
    foreach ($array as $value) {
        $count += substr_count(strtolower($value), strtolower($posword));
    }
    echo "Word: ".strtolower($posword)."      Count: ".$count."</br>";
}
//return $count;
?>

首先我加载单词列表。然后我有一个名为$ array的文本数组。然后我在每个单词之间循环,对于每个单词,我检查该单词是否出现在带有第二个循环的文本中。 然后对于每个循环,我回显该单词的计数。

当U strtolower($ posword)时,它总是导致0无所不能。当我将其更改为单个单词(如“value”)时,我会获得更高的计数。然后它只是将每个单词+ 1添加到计数变量。

任何人都可以弄清楚我做错了什么?提前谢谢。

P.S:最终目标是从出现的单词中创建一个标签云。

1 个答案:

答案 0 :(得分:0)

如果您尝试为标记云构建计数,我想我不会理解当前代码中的单个$count值。我认为您需要获取$poswords数组中每个单词的出现次数。你应该能够这样做:

$poswords = file('positive.csv', FILE_IGNORE_NEW_LINES);

// create an array to count your words,
// populated with words as keys and 0 as initial value
$word_counts = array_fill_keys($poswords, 0);

// your array of haystack strings
$array = array("value", "bar", "ACCOMPLISHES", "valveworld", "able I am not bladiebla");

// loop through each haystack string
foreach ($array as $haystack) {
    foreach($poswords as $needle) {    
        $match_count = substr_count(strtolower($haystack), strtolower($needle));
        $word_counts[$needle] += $match_count;
    }
}
var_dump($word_counts);