为了账号安全,请及时绑定邮箱和手机立即绑定

查找数组中单词长度的出现

查找数组中单词长度的出现

PHP
万千封印 2022-07-22 19:36:31
我正在尝试查找数组中出现的次数长度;这是我尝试过的,但我不知道之后该怎么做。function instances_and_count($input) {    $arr = explode(' ', $input);    $count = 0;    $test = [];    foreach ($arr as $arr_str) {        if ($count != 0) {            $test = [$count => 'hi'];            print_r($test);        }        $count++;    }}$test = 'A heard you say something I know you ain\'t trying to take me homeboy.';instances_and_count($test);在这个例子中,我分解一个字符串来创建一个数组。我需要计数让我们说所有长度为 1 的单词,在这个字符串中它的计数为 2(A 和 I);我怎样才能做到这一点?
查看完整描述

2 回答

?
慕姐8265434

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

)

这对于在您的应用程序中使用不是必需的。


查看完整回答
反对 回复 2022-07-22
?
白板的微信

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


查看完整回答
反对 回复 2022-07-22
  • 2 回答
  • 0 关注
  • 183 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号