[英]creating an array whose key and value is defined
下面的代碼基本上將計算單詞在數組中的出現次數。
我現在想做的是獲取$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/>";
}
}
試試這個代碼:
<?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
)
在將所有單詞完全分組在一起之前,您無法在循環內回顯計數值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.