php变量中重复项的计数

时间:2015-02-18 19:48:24

标签: php

HELOO,

我有一个PHP变量,如:

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

我想要计算每个重复的名称并打印出来像:

John
Mark (3)
Julian (2)

2 个答案:

答案 0 :(得分:2)

如果将字符串转换为数组,array_count_values()函数可以很好地适合。

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

计数数组:

Array
(
    [Mark] => 3
    [John] => 1
    [Julian] => 2
)

答案 1 :(得分:0)

你可以这样做:

$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)