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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。