我有一个数据库,其中一个表包含两列 FirstName
和 LastName
我的名字是 Bruce Wayne
,所以我想要的是一个输出:
一个 10%
乙 1 10%
c 1 10%
2 20%
n 1 10%
1 10%
你 1 10%
瓦 1 10%
是 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。谢谢!
最佳答案
首先拆分一个数组中的所有字母。数数组。遍历数组并计算我们看到它们的频率。然后再循环一次打印出结果:
<?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%
关于php - 计数字符并获取在 Php 或 SQL 中出现的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36915902/