在 PHP 中动态计算数组中元素的频率



我有一个数组说:

$array = array(1, 5, 2, 3, 3, 4, 5, 1)

我想转换这个数组并将值作为键,将其频率作为值输出应如下所示:

$array = array (
         "1" => 2,
         "2" => 1,
         "3" => 2,
         "4" => 1,
         "5" => 2
)

我知道如何在python中做到这一点。但我必须在PHP中做到这一点。我已经用下面的代码在python中实现了这个:蟒蛇代码:

d = {}
for j in tweets: // tweet is a array of integers as given above $array
d[j] = d.get(j, 0) + 1 // This will make a dictionary with the values in the array as key and its frequency as value of the dictionary .. Get() dynamically increase the value

请帮忙。

$newArray = array_count_values( $array );

在这里看到它的实际效果:http://codepad.org/n35PZ26I


要按键对其进行排序,请使用ksort

ksort( $newArray );

在这里看到它的实际效果:http://codepad.org/ZN0zHn4S

最新更新