创建一个其键和值已定义的数组

时间:2012-07-26 00:49:13

标签: php

下面的代码基本上会计算数组中单词出现的次数。

我现在想要发生的是获取$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/>";                       
    }
}

1 个答案:

答案 0 :(得分: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
)

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