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

时间:2015-04-06 19:56:40

标签: php arrays echo array-filter

如果有更好(更快)的方式输出重复的数组值及其在php中的计数,我需要你的建议。

目前,我正在使用以下代码:

初始输入始终是这样的文本字符串:

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

然后我得到唯一的数组值:

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

然后我计算数组中的重复值(不包括空值):

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

最后,我通过循环内的循环回显数组值及其计数:

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

我想知道是否有更好的方法来输出唯一值及其计数而不在循环内使用循环。

目前我选择了这种方法,因为:

  1. 我的输入始终是文本字符串
  2. 文本字符串包含空值,末尾有逗号
  3. 我只需回显非空值
  4. 请告诉我您的专家意见!

2 个答案:

答案 0 :(得分:1)

你可以编写你的代码来打印更短的值(我还写了更短的其他东西):

您不需要rtrim()array_unique(),只需要explode(),而array_filter()则需要处理空值。然后只需使用array_count_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)";

?>

输出:

a (2)b (2)c (2)d (2)e (1)f (1)g (1)

答案 1 :(得分:1)

您不需要制作两个数组,因为array_count_values键是文本的值。

$myArray = array_count_values(array_filter(explode(',',$text)));
foreach($myArray as $key => $value){
    echo $key . ' (' . $value . ')';
}