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 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)