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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置