猿问

将数组加在一起并显示每个字母使用了多少次

几个小时以来我一直在尝试自己寻找解决方案。尝试不同的方法。我需要将一列中的所有名称加在一起,并找出每个字母出现的次数。


这就是我陷入困境的地方,它只获取列中的名字并显示有关它的信息,但我需要将它们全部放在一起


$text=mysqli_query($conn,"SELECT test from tabletest");

//Fetch result 

$text=mysqli_fetch_assoc($text);

$my_id=$text['test'];


$text = str_replace(' ', '', $text );

$arrLetters = str_split($text['test']);

$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)."%\n";


临摹微笑
浏览 95回答 1
1回答

动漫人物

如果你想计算字符串数组中每个字母的频率,你可以使用mb_str_split()和array_count_values()例如,我的数据库中有两行:foo barthis 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 resultsforeach (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%
随时随地看视频慕课网APP
我要回答