dongmi5015 2017-04-10 23:50
浏览 23
已采纳

如何计算数组中的重复值?

I have a series of user data which each one is a list of comma separate values like italian, english. So first of all I want to list each of them and that it is fine and works. But these values could be repeated and it is ok yet I would like to know the number of the repeat values in order to be able to says: American = 2. The code below shows me

Duplicates count: 5

But actually I should have only 2 duplicates as I can see from the admin panel

$stack = array();
$blogusers = get_users( 'orderby=nicename&role=author' );
foreach ( $blogusers as $user ) {
    $descTokens = explode(',', $user->user_description);
    $stack = array_merge($stack, $descTokens);
}
$count_values = array();
foreach ($stack as $a) {
    @$count_values[$a]++;
}
echo 'Duplicates count: '.count($count_values);

If I do print_r($count_values) i get

Array ( [francese] => 1 [ matematica] => 2 [ inglese] => 1 [fisica] => 1 [ latino] => 1 ) Duplicates count: 5

And those aren't repeated strings

  • 写回答

3条回答 默认 最新

  • douhong9210 2017-04-11 00:15
    关注

    Add this at the end of your code to only have duplicates in $count_values

    $total_duplicates = 0;
    foreach ($count_values as $key=>$count) {
        if($count<=1){
            unset($count_values[$key]);
        }else{
            $total_duplicates += $count;
        }
    }
    

    This will remove any entries that are not duplicate (occuring once) via unset(). Also $total_duplicates will give you the total count of duplicates.

    To output that as html do this:

    echo '<p>You have '.$total_duplicates.' duplicates.</p>';
    foreach ($count_values as $key=>$count) { 
        echo '<li>'.$key.' '.$count.'</li>'; 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化