0

下面的代码基本上将计算一个单词在数组中出现的次数。

不过,我现在想要做的是获取$word,将其分配为数组的键,然后分配$WordCount[$word]为其值。例如,如果我得到一个单词“jump”,它将自动分配为数组的键,并将单词“jump”( $WordCount[$word]) 的出现次数分配为其值。请问有什么建议吗?

function Count($text)
{
    $text = strtoupper($text);
    $WordCount = str_word_count($text, 2);

    foreach($WordCount as $word)
    {   
        $WordCount[$word] = isset($WordCount[$word]) ? $WordCount[$word] + 1 : 1;
        echo "{$word} has occured {$WordCount[$word]} time(s) in the text <br/>";                       
    }
}
4

1 回答 1

1

试试这个代码:

<?php

$str = 'hello is my favorite word.  hello to you, hello to me.  hello is a good word';

$words = str_word_count($str, 1);

$counts = array();
foreach($words as $word) {
    if (!isset($counts[$word])) $counts[$word] = 0;
    $counts[$word]++;
}

print_r($counts);

输出:

Array
(
    [hello] => 4
    [is] => 2
    [my] => 1
    [favorite] => 1
    [word] => 2
    [to] => 2
    [you] => 1
    [me] => 1
    [a] => 1
    [good] => 1
)

在将所有单词完全组合在一起之前,您无法在循环中回显计数值。

于 2012-07-26T00:58:59.153 回答