doujiu1447 2015-04-06 19:56
浏览 55
已采纳

什么是在php中回显重复数组值及其计数的最佳/最快方法

I need your advice if there is a better (and faster) way to output duplicate array values and their count in php.

Currently, I am doing it with the below code:

The initial input is always a text string like this:

$text = "a,b,c,d,,,e,a,b,c,d,f,g,"; //Note the comma at the end

Then I get the unique array values:

$arrText = array_unique(explode(',',rtrim($text,',')));

Then I count the duplicate values in the array (excluding the empty ones):

$cntText = array_count_values(array_filter(explode(',', $text)));

And finally I echo the array values and their count with a loop inside a loop:

foreach($arrText as $text){
       echo $text;
       foreach($cntText as $cnt_text=>$count){
              if($cnt_text == $text){
                    echo " (".$count.")";
              }
}

I am wondering if there is a better way to output the unique values and their count without using a loop inside a loop.

Currently I have chosen this approach because:

  1. My input is always a text string
  2. The text string contains empty values and has a comma at the end
  3. I need to echo only non empty values

Let me know your expert advices!

  • 写回答

2条回答 默认 最新

  • dqaxw44567 2015-04-06 20:01
    关注

    You can write your code to print the values a lot shorter (Also I wrote other things a bit shorter):

    You don't need rtrim() or array_unique(), you only need explode() and with array_filter() you take care of the empty values. Then just use array_count_values() and loop through the values.

    <?php
    
        $text = "a,b,c,d,,,e,a,b,c,d,f,g,";
        $filtered = array_filter(explode(",", $text));
        $countes = array_count_values($filtered);
    
        foreach($countes as $k => $v)
            echo "$k ($v)";
    
    ?>
    

    output:

    a (2)b (2)c (2)d (2)e (1)f (1)g (1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里