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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址