dpchen2004
2015-02-18 19:48 阅读 15
已采纳

php变量中重复项的计数

HELOO ,

I have a PHP Variable like :

$var = 'Mark,John,Julian,Mark,Mark,Julian';

i want count every duplicate name and print them like :

John
Mark (3)
Julian (2)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dspv70887 dspv70887 2015-02-18 19:52

    You can do that like this:

    $var = 'Mark,John,Julian,Mark,Mark,Julian';
    $array = [];
    
    foreach(explode(',', $var) as $name){
        if(isset($array[trim($name)]))
            $array[trim($name)]++;
        else
            $array[trim($name)] = 1;
    }
    
    foreach($array as $name => $count){
        echo $name . ($count > 1 ? ' (' . $count . ')' : '') . '<br />';
    }
    
    //prints: 
    Mark (3)
    John
    Julian (2)
    
    点赞 评论 复制链接分享
  • doushang9172 doushang9172 2015-02-18 19:52

    the array_count_values() function could fit perfectly if you convert the string into an array.

    $var = 'Mark,John,Julian,Mark,Mark,Julian';
    $arr = explode(',', $var);
    $count = array_count_values($arr);
    

    Count array:

    Array
    (
        [Mark] => 3
        [John] => 1
        [Julian] => 2
    )
    
    点赞 评论 复制链接分享

相关推荐