1 回答
TA贡献1815条经验 获得超10个赞
如果你想计算字符串数组中每个字母的频率,你可以使用mb_str_split()
和array_count_values()
例如,我的数据库中有两行:
foo bar
this is a test of emoji 🎈
考虑以下代码。在这里,我使用mb_str_split()然后使用另一个foreach循环将循环内的每个值拆分为单独的字符,然后array_count_values($arrLetters)计算每个字符的频率。
$stmt = $conn->prepare("SELECT test from tabletest");
$stmt->execute();
$result = $stmt->get_result();
foreach ($result as $row) {
// split the string into characters
$arrLetters = mb_str_split($row['test']);
$countLetters = count($arrLetters);
// count frequence of each character and immediately display results
foreach (array_count_values($arrLetters) as $letter => $total) {
echo $letter.": ".$total.": ".round(($total / $countLetters * 100), 2)."%\n";
}
echo '--------------'.PHP_EOL;
}
它将产生以下输出:
f: 1: 14.29%
o: 2: 28.57%
: 1: 14.29%
b: 1: 14.29%
a: 1: 14.29%
r: 1: 14.29%
--------------
t: 3: 12%
h: 1: 4%
i: 3: 12%
s: 3: 12%
: 6: 24%
a: 1: 4%
e: 2: 8%
o: 2: 8%
f: 1: 4%
m: 1: 4%
j: 1: 4%
🎈: 1: 4%
--------------
如果您想将所有行的频率作为一个结果,那么您可以将其全部分解为一个字符串,并且无需循环即可完成。
$stmt = $conn->prepare("SELECT test from tabletest");
$stmt->execute();
$result = $stmt->get_result();
// Implode it all into a single string
$text = implode(array_column($result->fetch_all(MYSQLI_NUM), 0));
// split the string into characters
$arrLetters = mb_str_split($text);
$countLetters = count($arrLetters);
// count frequence of each character and immediately display results
foreach (array_count_values($arrLetters) as $letter => $total) {
echo $letter.": ".$total.": ".round(($total / $countLetters * 100), 2)."%\n";
}
这会给你这个输出:
f: 2: 6.25%
o: 4: 12.5%
: 7: 21.88%
b: 1: 3.13%
a: 2: 6.25%
r: 1: 3.13%
t: 3: 9.38%
h: 1: 3.13%
i: 3: 9.38%
s: 3: 9.38%
e: 2: 6.25%
m: 1: 3.13%
j: 1: 3.13%
🎈: 1: 3.13%
- 1 回答
- 0 关注
- 94 浏览
添加回答
举报