如何计算php中的重复数组值?

时间:2015-12-25 02:53:23

标签: php arrays

我有一个重复值的数组。

我想要打印所有项目但也要重复值,我也要打印一个数字。

像这样:

$arr = array('sara','jorj','sara','sara','jorj','eli','ana')

foreach($arr as $name)
{
   echo $name;
}

如何打印此结果:

sara
jorj
sara-2
sara-3
jorj-2
eli
ana

2 个答案:

答案 0 :(得分:8)

这应该适合你:

这里我首先使用array_slice()来获取迭代当前元素之前的所有元素的数组,例如

BOOL bRet;

while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0)
{ 
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else  // you could do whatever you want with the message before it is dispatched
    {
        TranslateMessage(&msg); 
        DispatchMessage(&msg); 
    }
}

然后我将这个数组与array_filter()一起使用,只保持值等于当前迭代值,所以我可以告诉当前值之前数组中有多少相同的值。

现在我只需要count()有多少,如果有多于1,我们也会在输出中打印它。

代码:

iteration value   |  sliced array
-----------------------------------
     sara         |       []
     jorj         |     [sara]

输出:

$arr = array('sara','jorj','sara','sara','jorj','eli','ana');

foreach($arr as $key => $name) {
    $count = count(array_filter(array_slice($arr, 0, $key), function($v)use($name){
       return $v == $name;
    })) + 1;

   echo $name . ($count > 1 ? " - $count" : "") . PHP_EOL;
}

答案 1 :(得分:2)

也许我对这个答案有点迟了,但继续我的尝试

$arr = array('sara','jorj','sara','sara','jorj','eli','ana');
$tmp = array();

foreach ($arr as $value) {
    if (!isset($tmp[$value]) ) {
        // if $value is not found in tmp array
        // initialize the value in tmp array and set to 1
        $tmp[$value] = 1;
        echo $value;
    }
    else {
        // found the value in tmp array
        // add 1 to the value in tmp array
        // output its current total count of this value
        $tmp[$value] += 1;
        echo "$value-", $tmp[$value]; 
    }
    echo "<br>";
}

输出:

sara
jorj
sara-2
sara-3
jorj-2
eli
ana

这实际上具有array_count_values的相同输出,但是分成了它的形式......我想