简体   繁体   English

用PHP计算单词中的字母数

[英]Counting the number of letters in a word by PHP

I want to create an array which has two columns. 我想创建一个具有两列的数组。 The output should contain only the existing letters in the word with their amounts. 输出中应仅包含单词中现有的字母及其数量。

The wanted output of the following code 以下代码的所需输出

a 3
s 2
p 1

What is wrong in the following PHP code? 以下PHP代码有什么问题?

<?php

$alpha = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','z','y');

$word = "saapas";

for ( $i = 0; $i < count($word); $i++ ) {
        echo $word[$i] . "\n";

        $table[$word[$i]][]++;           // Problem here
}


// array_unique, array_combine and some method which can sort arrays by alphabets can be useful 

PHP has extensive array functions that do much of the heavy lifting for this: PHP具有广泛的数组函数 ,为此可以完成很多繁重的工作:

$keys = range('a', 'z');
$values = array_fill(0, 26, 0);
$freq = array_combine($keys, $values);
$word = "saapas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
  $letter = strtolower($word[$i]);
  if (array_key_exists($letter, $freq)) {
    $freq[$letter]++;
  }
}
print_r($freq);

Output: 输出:

Array
(
    [a] => 3
    [b] => 0
    [c] => 0
    [d] => 0
    [e] => 0
    [f] => 0
    [g] => 0
    [h] => 0
    [i] => 0
    [j] => 0
    [k] => 0
    [l] => 0
    [m] => 0
    [n] => 0
    [o] => 0
    [p] => 1
    [q] => 0
    [r] => 0
    [s] => 2
    [t] => 0
    [u] => 0
    [v] => 0
    [w] => 0
    [x] => 0
    [y] => 0
    [z] => 0
)

If you want to distinguish between uppercase and lowercase try: 如果要区分大写和小写,请尝试:

$keys = array_merge(range('a', 'z'), range('A', 'Z'));
$values = array_fill(0, 52, 0);
$freq = array_combine($keys, $values);
$word = "saApas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
  $letter = $word[$i];
  if (array_key_exists($letter, $freq)) {
    $freq[$letter]++;
  }
}
print_r($freq);

Or to count any characters: 或计算任何字符:

$freq = array();
$word = "saApas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
  $letter = $word[$i];
  if (array_key_exists($letter, $freq)) {
    $freq[$letter]++;
  } else {
    $freq[$letter] = 1;
  }
}
print_r($freq);

This works using your input characters array, but do you really want to build a static array for this task? 这可以使用您的输入字符数组来工作,但是您真的要为此任务构建一个静态数组吗?

$table = array();
$count = strlen($word);
for ( $i = 0; $i < $count; $i++ ) {
    $letter = $word[$i];
    if ( !isset($table[$letter]) )
    {
        $table[$letter] = 0;
    }
    ++$table[$letter];
}

Here's a method of doing the same thing, but utilizing PHP's native functions: 这是一种执行相同操作的方法,但是利用了PHP的本机功能:

$ascii = count_chars($word, 1);
$keys = array_keys($ascii);
$chars = array_map('chr', $keys);
$charCount = array_values($ascii);
$table = array_combine($chars, $charCount);

Why complicate? 为什么会变得复杂?

$string = 'the grey fox jumps over the lazy dog';
$words = explode(' ', $string);

foreach ($words as $key => $value)
{
    $words[$key] = count_chars($value, 1);
}

echo '<pre>';
print_r($words);
echo '</pre>';
    for ( $i = 0; $i < $alpha.length; $i++ ) {

        $count = 0;
        for($a = 0; $a < count($word); $a++)
        {
            if($word[$a] == $array[$i]
                $count++;
        }
        if($count > 0)
             echo $array[$i] . " " . $count . "\n";

    }

So we use 2 for loops. 因此,我们将2用于循环。 A little inefficient that what your trying to do. 您尝试执行的操作效率低下。 One to check for each character of the alphabet. 一个检查字母的每个字符。 The second loop is to loop through the string and count the matches against the alphabet the first loop is on. 第二个循环是循环遍历字符串,并根据第一个循环所在的字母计数匹配项。

Edit: Or you could add a zero to the line below and remove the echo from the loop. 编辑:或者,您可以在下面的行中添加零,并从循环中删除回显。 Which still requires another loop to display this table. 仍然需要另一个循环才能显示此表。

$table[$word[$i]][0]++;

try this out.it is a single iteration method and faster and simple! 试试看。这是一个单一的迭代方法,更快,更简单!

<?php

$word = "saapas";
$result;
for ( $i = 0; $i < strlen($word); $i++ ) {
        echo $word[$i] . "\n";
        $result[$word[$i]]++; //make use of associative arrays to store the count for each alphabet.
}
foreach($result as $key => $value)//print each element inside the result array
{
print $key . " = " . $value . "<br />";
}
?>

count() doesn't quite work that way, you have to explicitly convert to an array if you want to use the count function. count()并非完全如此,如果要使用count函数,则必须显式转换为数组。 As for the $table array, you have an extra dimension (the []). 至于$ table数组,则有一个额外的维度([])。

The following code should work (it is not optimal but should get you pointed in the right direction.) 以下代码应该可以工作(这不是最佳选择,但应该使您朝正确的方向发展。)

$word = str_split("saapas");

for ( $i = 0; $i < count($word); $i++ ) {
    $table[$word[$i]]++;
}

foreach ($table as $key => $value) {
    print "$key $value\n";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM