Php 查找数组中出现的字长

Php 查找数组中出现的字长,php,Php,我试图找到数组中出现的次数 这是我试过的,但我不知道以后该怎么办 function instances_and_count($input) { $arr = explode(' ', $input); $count = 0; $test = []; foreach ($arr as $arr_str) { if ($count != 0) { $test = [$count => 'hi'];

我试图找到数组中出现的次数

这是我试过的,但我不知道以后该怎么办

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的所有单词的计数,在这个字符串中,它的计数是2a和I;如何对所有长度执行此操作?

将单词的长度用作数组键。对于要循环的每个单词,检查该长度的数组条目是否已经存在-如果已经存在,请将该值增加1,否则在该点用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

PHP的数组函数在这里非常有用;我们可以使用and将d字符串数组转换为字符串长度数组,然后使用计算每个长度的单词数:

$test = 'A heard you say something I know you ain\'t trying to take me homeboy.';
$counts = array_count_values(array_map(function ($v) { return strlen($v); }, explode(' ', $test)));
print_r($counts);
输出:

Array
(
    [1] => 2
    [5] => 2
    [3] => 3
    [9] => 1
    [4] => 2
    [6] => 1
    [2] => 2
    [8] => 1
)
Array
(
    [1] => 2
    [2] => 2
    [3] => 3
    [4] => 2
    [5] => 2
    [6] => 1
    [8] => 1
    [9] => 1
)
如果要按顺序输出带有键的数组,请先在其上使用:

ksort($counts);
print_r($counts);
输出:

Array
(
    [1] => 2
    [5] => 2
    [3] => 3
    [9] => 1
    [4] => 2
    [6] => 1
    [2] => 2
    [8] => 1
)
Array
(
    [1] => 2
    [2] => 2
    [3] => 3
    [4] => 2
    [5] => 2
    [6] => 1
    [8] => 1
    [9] => 1
)

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

谢谢Nick,这正是我要找的。@EricEvans不用担心-我很高兴能帮上忙