2 回答
TA贡献1813条经验 获得超2个赞
PHP 的数组函数在这里非常有用;我们可以使用and将我们的exploded 字符串数组转换为字符串长度数组,然后使用来计算每个长度有多少单词:array_mapstrlenarray_count_values
$test = 'A heard you say something I know you ain\'t trying to take me homeboy.';
$counts = array_count_values(array_map('strlen', explode(' ', $test)));
print_r($counts);
输出:
Array
(
[1] => 2
[5] => 2
[3] => 3
[9] => 1
[4] => 2
[6] => 1
[2] => 2
[8] => 1
)
3v4l.org 上的演示
请注意,此数组中“单词”的长度为 8,homeboy.这可以通过从字符串中去除尾随标点符号来避免,或者(更好地)使用str_word_count从原始字符串中仅提取整个单词。例如(感谢@mickmackusa):
$test = 'I heard you say something I know you ain\'t trying to take me homeboy.';
$counts = array_count_values(array_map('strlen', str_word_count($test, 1)));
print_r($counts);
输出:
Array
(
[1] => 2
[5] => 2
[3] => 3
[9] => 1
[4] => 2
[6] => 1
[2] => 2
[7] => 1
)
3v4l.org 上的演示
如果要按顺序输出带有键的数组,只需ksort先使用它:
ksort($counts);
print_r($counts);
输出:
Array
(
[1] => 2
[2] => 2
[3] => 3
[4] => 2
[5] => 2
[6] => 1
[8] => 1
[9] => 1
)
这对于在您的应用程序中使用不是必需的。
TA贡献1883条经验 获得超3个赞
使用单词的长度作为数组键。对于您正在循环的每个单词,检查该长度的数组条目是否已经存在 - 如果存在,则将该值增加一,否则在该点将其初始化为 1:
function instances_and_count($input) {
$words = explode(' ', $input);
$wordLengthCount = [];
foreach($words as $word) {
$length = strlen($word);
if(isset($wordLengthCount[$length])) {
$wordLengthCount[$length] += 1;
}
else {
$wordLengthCount[$length] = 1;
}
}
ksort($wordLengthCount);
return $wordLengthCount;
}
结果:
array (size=8)
1 => int 2
2 => int 2
3 => int 3
4 => int 2
5 => int 2
6 => int 1
8 => int 1
9 => int 1
- 2 回答
- 0 关注
- 183 浏览
添加回答
举报
