计数字符并获得 Php 或 SQL 中出现的百分比

Count characters and get percentage of occurrence in Php or SQL

我的数据库有一个 table 两列 FirstNameLastName 我的名字是 Bruce Wayne,所以我想要的是这样的输出:

a 1 10% B 1 10% c 1 10% e 2 20% n 1 10% r 1 10% u 1 10% W 1 10% y 1 10%

每个字符在两个名字中出现了多少次,总体出现的百分比是多少。 我是 php 和 mysql 的新手,欢迎提供一点帮助。 到目前为止,我已经找到了这个 http://php.net/manual/en/function.substr-count.php

$text = 'This is a test';
echo strlen($text); // 14

echo substr_count($text, 'is'); // 2

我不知道最好的方法是 php 还是 sql。谢谢!

您问过:

I don't know if the best approach would be php or sql.

对于这个字符频率应用程序,您应该使用 MySQL 查询获取字符串并计算它们在 php 客户端语言中的频率。

可以编写一些MySQL代码来执行服务器端的计数,但这会相当复杂。

首先拆分数组中的所有字母。数数组。遍历数组并计算我们看到它们的频率。然后再循环一次打印出结果:

<?php
$text = 'This is a test';
$text = str_replace(' ', '', $text );
$arrLetters = str_split($text);
$countLetters = count($arrLetters);

$letters = [];

foreach($arrLetters as $letter){
    if(isset($letters[$letter])){
        $letters[$letter] += 1;
    } else {
        $letters[$letter] = 1;  
    }
}

foreach($letters as $letter => $total){
    echo $letter.":".$total.":".round(($total/$countLetters*100),2)."%<br />";
}

结果:

T:1:9.09%
h:1:9.09%
i:2:18.18%
s:3:27.27%
a:1:9.09%
t:2:18.18%
e:1:9.09%