如何从数组中输出包含四个或更多字母的单词并说明它们出现的次数?
$selection = array("house", "are", "better", "love", "dog",
"love", "don't", "me", "like", "apples", "frank", "better", "you",
"like", "house", "better", "love", "cream");
$array2 = array();
foreach ($selection as $word) {
if (strlen($word) >= 4) {
$array2[] = $word;
print_r(array_count_values($word));
}
}
return $array2;
foreach ($array2 as $key => $value) {
printf("The word '$key' appears $value times<br>\n");
}
答案 0 :(得分:0)
您的代码中存在几个问题。您应该使用单词作为数组键,并保持运行计数。
此外,您正在调用return
,这会有效地停止脚本。
最后,使用更多描述性变量名称来帮助跟踪您正在做的事情。
<?php
$selection = array("house", "are", "better", "love", "dog",
"love", "don't", "me", "like", "apples", "frank", "better", "you",
"like", "house", "better", "love", "cream");
$results = array();
foreach ($selection as $word) {
if (strlen($word) >= 4) {
if (array_key_exists($word, $results) == false)
$results[$word] = 0;
$results[$word]++;
}
}
foreach ($results as $word=>$count) {
print "The word '$word' appears $count times<br>\n";
}
?>
http://codepad.viper-7.com/pq89ic
文档&amp;相关阅读
return
- http://us1.php.net/return 答案 1 :(得分:0)
执行此操作:
<?
$selection = array("house", "are", "better", "love", "dog",
"love", "don't", "me", "like", "apples", "frank", "better", "you",
"like", "house", "better", "love", "cream");
$array2 = array();
foreach ($selection as $word) {
if (strlen($word) >= 4) {
if (isset($array2[$word])) $array2[$word]++;
else $array2[$word] = 1;
}
}
foreach ($array2 as $key => $value) {
printf("The word '$key' appears $value times<br>\n");
}
?>
<强> SEE WORKING CODE 强>